我已经在Adonis中实现了使用访问令牌注册和登录。
我的问题是注销 api 调用,我不知道如何访问令牌。我尝试了几种方法:
async logout({ auth }: HttpContextContract) {
const apiAuth1 = auth.token // undefined
const apiAuth2 = auth.use('api').token // undefined
const apiAuth3 = await auth.use('api').getAuth() // auth.use(...).getAuth is not a function
我相信访问令牌是可以访问的,因为我在注销操作中进行了以下测试:
async logout({ auth }: HttpContextContract) {
const check = await auth.check('api')
console.log('check: ', check, typeof check)
const user = auth.user
console.log('user: ', JSON.stringify(user, null, 2))
const apiAuth = auth.use('api')
// Debug the entire apiAuth object
console.log('apiAuth:', JSON.stringify(apiAuth, null, 2))
}
这给了我:
check: true boolean
user: {
"id": 27,
"fullName": "John Doe",
"email": "[email protected]",
"createdAt": "2024-06-03T20:12:35.000+00:00",
"updatedAt": "2024-06-03T20:12:35.000+00:00"
}
apiAuth: {
"driverName": "access_tokens",
"authenticationAttempted": true,
"isAuthenticated": true,
"user": {
"id": 27,
"fullName": "John Doe",
"email": "[email protected]",
"createdAt": "2024-06-03T20:12:35.000+00:00",
"updatedAt": "2024-06-03T20:12:35.000+00:00"
}
}
当然,该操作受到 AuthMiddleware 的保护,如下所示:
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'
import type { Authenticators } from '@adonisjs/auth/types'
/**
* Auth middleware is used authenticate HTTP requests and deny
* access to unauthenticated users.
*/
export default class AuthMiddleware {
async handle(
ctx: HttpContext,
next: NextFn,
options: {
guards?: (keyof Authenticators)[]
} = {}
) {
const res = await ctx.auth.authenticateUsing(options.guards)
return next()
}
}
可能会迟到,但我想这是解决方案。
您可以通过
user.currentAccessToken
获取用户的访问令牌
您可以使用 user.currentAccessToken.identifier
获取它的标识符
然后,您可以使用
User.accessTokens.delete(user, user.currentAccessToken.identifier)
将其从数据库中删除
你可以做这样的事情:
async logout({ auth, response }: HttpContext) {
const user = auth.getUserOrFail()
const token = user.currentAccessToken.identifier
if (!token) {
return response.unauthorized('Invalid token')
}
await User.accessTokens.delete(user, token)
return response.ok('Logged out successfully')
}