該Authorization: Basic ...
頭可以被用于發(fā)送用戶名和密碼憑據(jù)進(jìn)行身份驗(yàn)證毕箍。
此頁(yè)面將向您展示如何在您的網(wǎng)絡(luò)應(yīng)用程序中使用此類型的身份驗(yàn)證抽高。
注意
應(yīng)盡可能避免發(fā)送和存儲(chǔ)密碼。使用令牌或會(huì)話持久性柑蛇,以防止在每個(gè)請(qǐng)求中發(fā)送密碼。
密碼認(rèn)證(Password Authenticatable)
首先將您的用戶模型繼承PasswordAuthenticatable協(xié)議驱闷。
import AuthProvider
extension User: PasswordAuthenticatable { }
自定義(Custom)
如果您的用戶符合Model
要求耻台,則所有必需的方法將自動(dòng)實(shí)現(xiàn)。
但是空另,如果你想做一些自定義的操作盆耽,你可以實(shí)現(xiàn)它們。
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
/// 實(shí)體的散列密碼用于驗(yàn)證密碼PasswordVerifier憑證
var hashedPassword: String? {
// something custom 自定義的東西
}
/// The key under which the user's username,
/// email, or other identifing value is stored.
/// 的關(guān)鍵用戶的用戶名痹换、電子郵件或其他鑒別值存儲(chǔ)征字。
static var usernameKey: String {
// something custom 自定義的東西
}
/// The key under which the user's password
/// is stored.
/// 的關(guān)鍵是存儲(chǔ)用戶的密碼。
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.
/// 可選的密碼校驗(yàn)時(shí)使用比較的明文密碼授權(quán)頭哈希密碼在數(shù)據(jù)庫(kù)中娇豫。
static var passwordVerifier: PasswordVerifier? {
// some hasher
}
}
中間件(Middleware)
一旦您的model符合PasswordAuthenticatable
協(xié)議匙姜,就可以創(chuàng)建中間件。
import Vapor
import AuthProvider
let drop = try Droplet()
let passwordMiddleware = PasswordAuthenticationMiddleware(User.self)
let authed = try drop.grouped(passwordMiddleware)
try drop.run()
添加到authed
路由組的所有路由將受到密碼中間件的保護(hù)冯痢。
瞧一瞧
如果您只想全局要求密碼中間件氮昧,請(qǐng)檢查HTTP文檔中
的中間件配置部分框杜。
路由(Route)
現(xiàn)在,您可以添加路由以返回經(jīng)過(guò)身份驗(yàn)證的用戶袖肥。
authed.get("me") { req in
// return the authenticated user
return try req.auth.assertAuthenticated(User.self)
}
調(diào)用req.user.authenticated(User.self)
以訪問經(jīng)過(guò)身份驗(yàn)證的用戶咪辱。
請(qǐng)求(Request)
現(xiàn)在我們可以向我們的Vapor應(yīng)用程序發(fā)出請(qǐng)求。
GET /me HTTP/1.1
Authorization: Basic dmFwb3I6Zm9v
注意
dmFwb3I6Zm9v
是“vapor:foo”base64編碼椎组,其中“vapor”是用戶名油狂,“foo”是密碼。這是基本授權(quán)標(biāo)頭的格式寸癌。
我們應(yīng)該得到一個(gè)回應(yīng)专筷。
HTTP/1.1 200 OK
Content-Type: text/plain
Vapor