一个用于 Kitura-Credentials 框架的插件,它使用 HTTP Basic 和 Digest 认证进行身份验证。
一个用于 Kitura-Credentials 框架的插件,它使用 HTTP Basic 和 Digest 认证进行身份验证。
我们实现的 Digest 认证不记住它生成的 nonce 值,也不检查收到的请求的 nonce 和 nc。它使用 MD5 算法,并且保护质量 (qop) 为 'auth'。
最新版本的 Kitura-CredentialsHTTP 需要 Swift 4.0 或更高版本。您可以按照这个 链接 下载此版本的 Swift 二进制文件。不保证与其他 Swift 版本的兼容性。
将 Kitura-CredentialsHTTP
包添加到应用程序的 Package.swift
文件中的依赖项中。将 "x.x.x"
替换为最新的 Kitura-CredentialsHTTP
版本。
.package(url: "https://github.com/Kitura/Kitura-CredentialsHTTP.git", from: "x.x.x")
将 CredentialsHTTP
添加到目标依赖项
.target(name: "example", dependencies: ["CredentialsHTTP"]),
import CredentialsHTTP
要创建 CredentialsHTTPBasic
插件的实例,需要将 VerifyPassword
函数和一个可选的 realm 传递给构造函数
public init (verifyPassword: @escaping VerifyPassword, realm: String?=nil)
verifyPassword
是以下类型的函数
/// Type alias for the callback that verifies the userId and password.
/// If the authentication pair verifies, then a user profile is returned.
public typealias VerifyPassword = (userId: String, password: String, callback: @escaping (UserProfile?) -> Void) -> Void
CredentialsHTTPDigest 的初始化类似于 CredentialsHTTPBasic。此外,可以将一个可选的 opaque 值传递给构造函数。
首先创建一个符合 TypeSafeHTTPBasic
的结构体或 final 类,添加任何实例变量,您将在 verifyPassword
中初始化它们
import CredentialsHTTP
public struct MyBasicAuth: TypeSafeHTTPBasic {
public let id: String
static let users = ["John" : "12345", "Mary" : "qwerasdf"]
public static func verifyPassword(username: String, password: String, callback: @escaping (MyBasicAuth?) -> Void) {
if let storedPassword = users[username], storedPassword == password {
callback(MyBasicAuth(id: username))
} else {
callback(nil)
}
}
}
通过将您的 TypeSafeHTTPBasic
对象作为 TypeSafeMiddleware
添加到您的 codable 路由来为路由添加身份验证
router.get("/protected") { (userProfile: MyBasicAuth, respondWith: (MyBasicAuth?, RequestError?) -> Void) in
print("authenticated \(userProfile.id) using \(userProfile.provider)")
respondWith(userProfile, nil)
}
此示例展示了如何使用此插件通过 HTTP Basic 认证对请求进行身份验证。HTTP Digest 认证类似。
首先创建一个 Credentials
实例和一个 CredentialsHTTPBasic
插件实例,并提供一个 verifyPassword
函数
import Credentials
import CredentialsHTTP
let credentials = Credentials()
let users = ["John" : "12345", "Mary" : "qwerasdf"]
let basicCredentials = CredentialsHTTPBasic(verifyPassword: { userId, password, callback in
if let storedPassword = users[userId], storedPassword == password {
callback(UserProfile(id: userId, displayName: userId, provider: "HTTPBasic"))
} else {
callback(nil)
}
})
现在注册插件
credentials.register(plugin: basicCredentials)
将 credentials
中间件连接到 profile 请求
router.all("/profile", middleware: credentials)
如果身份验证成功,request.userProfile
将包含用户个人资料信息
router.get("/profile", handler:
{ request, response, next in
...
let profile = request.userProfile
let userId = profile.id
let userName = profile.displayName
...
next()
})
在构建时看到错误 ld: library not found for -lCHttpParser for architecture x86_64
吗?
要解决此问题,请转到 Xcode 构建设置,并将 $SRCROOT/.build/debug
添加到 CredentialsHTTP 目标的 Library Search Paths。
此库在 Apache 2.0 许可下发布。完整的许可证文本可在 LICENSE 中找到。