Vapor 2.0 - 用户名+密码(基本)认证(Usernam

2017-08-13  本文已影响0人  韩云智VL

前往 Vapor 2.0 - 文档目录

Authorization: Basic ...头可以被用于发送用户名和密码凭据进行身份验证。

此页面将向您展示如何在您的网络应用程序中使用此类型的身份验证。

注意
应尽可能避免发送和存储密码。使用令牌或会话持久性,以防止在每个请求中发送密码。

密码认证(Password Authenticatable)

首先将您的用户模型继承PasswordAuthenticatable协议。

import AuthProvider

extension User: PasswordAuthenticatable { }

自定义(Custom)

如果您的用户符合Model要求,则所有必需的方法将自动实现。
但是,如果你想做一些自定义的操作,你可以实现它们。

extension User: PasswordAuthenticatable {
    /// Return the user matching the supplied
    /// username and password
    ///返回用户匹配提供的用户名和密码
    static func authenticate(_: Password) throws -> Self {
        // something custom 自定义的东西
    }

    /// The entity's hashed password used for
    /// validating against Password credentials
    /// with a PasswordVerifier
    /// 实体的散列密码用于验证密码PasswordVerifier凭证
    var hashedPassword: String? {
        // something custom 自定义的东西
    }

    /// The key under which the user's username,
    /// email, or other identifing value is stored.
    /// 的关键用户的用户名、电子邮件或其他鉴别值存储。
    static var usernameKey: String {
        // something custom 自定义的东西
    }

    /// The key under which the user's password
    /// is stored.
    /// 的关键是存储用户的密码。
    static var passwordKey: String {
        // something custom 自定义的东西
    }

    /// Optional password verifier to use when
    /// comparing plaintext passwords from the 
    /// Authorization header to hashed passwords
    /// in the database.
    /// 可选的密码校验时使用比较的明文密码授权头哈希密码在数据库中。
    static var passwordVerifier: PasswordVerifier? {
        // some hasher
    }
}

中间件(Middleware)

一旦您的model符合PasswordAuthenticatable协议,就可以创建中间件。

import Vapor
import AuthProvider

let drop = try Droplet()

let passwordMiddleware = PasswordAuthenticationMiddleware(User.self)

let authed = try drop.grouped(passwordMiddleware)

try drop.run()

添加到authed路由组的所有路由将受到密码中间件的保护。

瞧一瞧
如果您只想全局要求密码中间件,请检查HTTP文档中
中间件配置部分。

路由(Route)

现在,您可以添加路由以返回经过身份验证的用户。

authed.get("me") { req in
    // return the authenticated user
    return try req.auth.assertAuthenticated(User.self)
}

调用req.user.authenticated(User.self)以访问经过身份验证的用户。

请求(Request)

现在我们可以向我们的Vapor应用程序发出请求。

GET /me HTTP/1.1
Authorization: Basic dmFwb3I6Zm9v 

注意
dmFwb3I6Zm9v是“vapor:foo”base64编码,其中“vapor”是用户名,“foo”是密码。这是基本授权标头的格式。

我们应该得到一个回应。

HTTP/1.1 200 OK
Content-Type: text/plain

Vapor
上一篇 下一篇

猜你喜欢

热点阅读