Kunkgg / authentication_course

Repo for Vue Mastery's Token-Based Authentication course

Home Page:https://www.vuemastery.com/courses/token-based-authentication/intro-to-authentication

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

test

This template should help get you started developing with Vue 3 in Vite.

Recommended IDE Setup

VSCode + Volar (and disable Vetur) + TypeScript Vue Plugin (Volar).

Customize configuration

See Vite Configuration Reference.

Project Setup

npm install

Compile and Hot-Reload for Development

npm run dev

Compile and Minify for Production

npm run build

start backend

node server.js

start

npm run start

目标

  1. 注册
  2. 登录
  3. 访问受保护的数据

注册及登录后 vuex 需要做 3 件事

  1. 在 Vuex state 中存储 userData
  2. 在 localstorage 中存储 userData
  3. 在 axios header 中增加 token

登出

  1. 清除 localstorage 中存储的 userData
  2. 清除 Vuex state 中的 userDate 和 axios header 中的 token, 使用 location.reload() 可以实现

navigation guard 仅登录用户可以访问受保护路由

  • /dashboard 路由增加 meta: {requireAthu: true}
  • router.beforeEach 判断当路由有 meta.requireAthu 时是否已登录,
    • 如果未登录, next('/')
    • 如果已登录, next()
  • 参考 Navigation Guards
  • 参考 Route Meta Fields

保持登录

  • 登录后, 刷新页面或者关闭页面标签仍保持登录状态
    • 从 localstorage 取出 userData, 调用 Vuex action

恶意伪造 token 处理

当攻击者试图使用伪造的 token 访问受保护资源, 中断并立即登出

    new Vue({
      router,
      store,
      created () {
    	...
    	axios.interceptors.response.use(
            response => response, // simply return the response 
    		error => {
    		    if (error.response.status === 401) { // if we catch a 401 error
    		     this.$store.dispatch('logout') // force a log out 
    		}
    		return Promise.reject(error) // reject the Promise, with the error as the reason
    	    }
    	)
      },
      render: h => h(App)
    }).$mount('#app')

About

Repo for Vue Mastery's Token-Based Authentication course

https://www.vuemastery.com/courses/token-based-authentication/intro-to-authentication


Languages

Language:Vue 55.3%Language:JavaScript 27.9%Language:CSS 15.3%Language:HTML 1.5%