Authentication module for Nuxt.js https://auth.nuxtjs.org
Github:https://github.com/nuxt-community/auth-module
Demo:https://nuxt-auth.herokuapp.com/
引入
npm install @nuxtjs/auth @nuxtjs/axios
配置
首先看看 nuxt.config.js
需要配置 modules 项 和 auth 项
modules: [
'@nuxtjs/axios',
'@nuxtjs/auth'
],
auth: {
// Options
}
来看个完整版的
const { resolve } = require('path')
module.exports = {
rootDir: resolve(__dirname, '../..'),
buildDir: resolve(__dirname, '.nuxt'),
srcDir: __dirname,
build: {
extractCSS: true
},
serverMiddleware: ['../api/auth'],
modules: ['bootstrap-vue/nuxt', '@nuxtjs/axios', '@@'],
axios: {
proxy: true
},
proxy: {
'/api': 'http://localhost:3000'
},
auth: {
redirect: {
callback: '/callback'
},
strategies: {
local: {
endpoints: {
login: { propertyName: 'token.accessToken' }
}
},
auth0: {
domain: 'nuxt-auth.auth0.com',
client_id: 'q8lDHfBLJ-Fsziu7bf351OcYQAIe3UJv'
},
facebook: {
client_id: '1671464192946675',
userinfo_endpoint: 'https://graph.facebook.com/v2.12/me?fields=about,name,picture{url},email,birthday',
scope: ['public_profile', 'email', 'user_birthday']
},
google: {
client_id:
'956748748298-kr2t08kdbjq3ke18m3vkl6k843mra1cg.apps.googleusercontent.com'
},
github: {
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET
},
twitter: {
client_id: 'FAJNuxjMTicff6ciDKLiZ4t0D'
}
}
}
}
有几个注意点,分别说一下
- serverMiddleware
这里的中间件是/api/auth.js
,下面会放这个文件的内容。
Path: /api/auth
POST /login 通过username password 验证,正确则签发JWT,返回 accessToken
GET /user 获取用户信息,实际代码
POST /logout
- strategy
github: {
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET
},
源代码里尽量使用 process.env
传入 id secret 等参数
页面
看 public 页面中的 script
<script>
export default {
middleware: ['auth'],
options: {
auth: false
}
}
</script>
看 secure 页面中的 script
<script>
export default {
middleware: ['auth'],
computed: {
state() {
return JSON.stringify(this.$auth.$state, undefined, 2)
}
}
}
</script>
跳转
整体流程
总结整体流程如下