我是 Vapor 的新手,我已经实现了注册和登录路由。注册工作正常。每次我调用登录路由时,它似乎都有问题。每次,我尝试使用基本身份验证以注册用户身份登录,它只返回 401。在下面附上我的代码。
应用用户模型:
extension AppUser: ModelAuthenticatable {
static let usernameKey = \AppUser.$email
static let passwordHashKey = \AppUser.$passwordHash
func verify(password: String) throws -> Bool {
try Bcrypt.verify(password, created: self.passwordHash)
}
}
extension AppUser: JWTPayload {
func verify(using signer: JWTSigner) throws {
}
}
路线配置:
//MARK: Unprotected API
let unprotectedApi = app.routes
try unprotectedApi.register(collection: AppUserController.Unprotected())
//MARK: Password Protected API
let passwordProtectedApi = unprotectedApi.grouped(AppUser.authenticator())
try passwordProtectedApi.register(collection: AppUserController.PasswordProtected())
登录逻辑:
extension AppUserController.PasswordProtected: RouteCollection {
func login(req: Request) throws -> EventLoopFuture<Response> {
let user = try req.auth.require(AppUser.self)
let token = try req.jwt.sign(user)
let loginResponse = AppUserLoginResponse(user: user.response, accessToken: token)
return DataWrapper.encodeResponse(data: loginResponse, for: req)
}
func boot(routes: RoutesBuilder) throws {
routes.post(Endpoint.API.Users.login, use: login)
}
}