@adonisjs/auth
模块npm i @adonisjs/auth
在 start/auth.js
文件中,引入 @adonisjs/auth
,然后添加 Bearer 授权策略:
'use strict'
const { ServiceProvider } = require('@adonisjs/fold')
const { HttpContext } = require('@adonisjs/http-context')
const { AllyManager } = require('@adonisjs/o-auth')
const { Config } = require('@adonisjs/config')
const { hooks } = require('@adonisjs/ignitor')
const PersManager = require('pers-layer')
class AuthServiceProvider extends ServiceProvider {
register () {
this.app.singleton('Adonis/Addons/Auth', (app) => {
const Config = app.use('Adonis/Src/Config')
const Hash = app.use('Adonis/Src/Hash')
const Database = app.use('Adonis/Src/Database')
const Ally = new AllyManager(Config)
const Pers = new PersManager(Config, Database)
return new (require('.'))(Config, Hash, Database, HttpContext, Ally, Pers)
})
}
boot () {
const { auth } = this.app
const Config = this.app.use('Adonis/Src/Config')
auth.extend('jwt', (guard, options, ctx) => {
const JwtGuard = require('./src/Guards/JwtGuard')
return new JwtGuard(guard, options, ctx.auth, Config)
})
// 添加 Bearer 授权策略
auth.extend('bearer', (guard, options, ctx) => {
const BearerGuard = require('./src/Guards/BearerGuard')
return new BearerGuard(guard, options, ctx.auth, Config)
})
hooks.after.providersBooted(() => {
const View = use('View')
const auth = use('Auth')
View.global('can', (permission) => {
return auth.user && auth.user.can(permission)
})
})
}
}
module.exports = AuthServiceProvider
在 start/auth.js