Kitura

Docs Build Status - Master macOS Linux Apache 2 Slack Status

Kitura-CredentialsJWT

一个使 Kitura 能够使用 JSON Web Tokens 验证用户身份的软件包。

概要

这个软件包提供以下两种功能:

Swift 版本

最新版本的 Kitura-CredentialsJWT 需要 Swift 4.0 或更高版本。 您可以通过此链接下载此版本的 Swift 二进制文件。 不保证与其他 Swift 版本的兼容性。

用法

添加依赖项

在应用程序的 Package.swift 文件中添加 Kitura-CredentialsJWT 依赖项。 将 "x.x.x" 替换为最新的 Kitura-CredentialsJWT 版本

.package(url: "https://github.com/Kitura/Kitura-CredentialsJWT.git", from: "x.x.x")

CredentialsJWT 添加到目标依赖项

.target(name: "example", dependencies: ["CredentialsJWT"]),

导入包

import CredentialsJWT

使用 CredentialsJWT 插件

此插件要求请求中存在以下 HTTP 标头:

Swift-JWT 库用于解码 Authorization 标头中提供的令牌。 要成功解码,您必须指定 JWT 中将存在的 Claims

一个声明(默认情况下,sub)将用于表示持有者的身份。 您可以通过在创建 CredentialsJWT 实例时提供 subject 选项来选择不同的声明,并且您可以通过定义 UserProfileDelegate 来进一步自定义生成的 UserProfile

### 用法示例

要使用默认选项使用 CredentialsJWT

import Credentials
import CredentialsJWT
import SwiftJWT

// Defines the claims that must be present in a JWT.
struct MyClaims: Claims {
    let sub: String
}

// Defines the method used to verify the signature of a JWT.
let jwtVerifier = .hs256(key: "<PrivateKey>".data(using: .utf8)!)

// Create a CredentialsJWT plugin with default options.
let jwtCredentials = CredentialsJWT<MyClaims>(verifier: jwtVerifier)

let authenticationMiddleware = Credentials()
authenticationMiddleware.register(plugin: jwtCredentials)
router.get("/myProtectedRoute", middleware: authenticationMiddleware)

成功验证后,UserProfile 将以两个必需字段(iddisplayName)进行最小填充,两者都具有 JWT 的 sub 声明的值。 provider 将设置为 JWT

用法示例 - 自定义声明

要自定义身份声明的名称,并进一步填充 UserProfile 字段,请按如下所示指定 subjectuserProfileDelegate 选项

import Credentials
import CredentialsJWT
import SwiftJWT

// Defines the claims that must be present in a JWT.
struct MyClaims: Claims {
    let id: Int
    let fullName: String
    let email: String
}

struct MyDelegate: UserProfileDelegate {
    func update(userProfile: UserProfile, from dictionary: [String:Any]) {
        // `userProfile.id` already contains `id`
        userProfile.displayName = dictionary["fullName"]! as! String
        let email = UserProfile.UserProfileEmail(value: dictionary["email"]! as! String, type: "home")
        userProfile.emails = [email]
    }
}

// Defines the method used to verify the signature of a JWT.
let jwtVerifier = .hs256(key: "<PrivateKey>".data(using: .utf8)!)

// Create a CredentialsJWT plugin with default options.
let jwtCredentials = CredentialsJWT<MyClaims>(verifier: jwtVerifier, options: [CredentialsJWTOptions.subject: "id", CredentialsJWTOptions.userProfileDelegate: MyDelegate])

let authenticationMiddleware = Credentials()
authenticationMiddleware.register(plugin: jwtCredentials)
router.get("/myProtectedRoute", middleware: authenticationMiddleware)

成功验证后,UserProfile 将按如下方式填充

Codable 路由的 JWT 身份验证示例

可以使用 JWT<C: Claims> 类型(由 Swift-JWT 定义)作为 Type-Safe Middleware,使用 JWT 对 Kitura Codable 路由进行身份验证

import SwiftJWT
import CredentialsJWT

// Define the claims that must appear in the JWT
struct MyClaims: Claims {
    // Subject's id (e.g. name)
    let sub: String
}

// Set up TypeSafeJWT by specifying the method for verifying a JWT signature
let key = "<PrivateKey>".data(using: .utf8)!
TypeSafeJWT.verifier = .hs256(key: key)

// Use the JWT type as a Type-Safe Middleware to protect a route. The handler will only be
// invoked if the JWT can be successfully verified, and contains the required claims.
router.get("/protected") {  (jwt: JWT<MyClaims>, respondWith: (User?, RequestError?) -> Void) in
    // (Decide whether to permit the user access to this resource, based on the JWT claims)
    // Send the requested resource:
    let user = User(name: jwt.claims.sub)
    respondWith(user, nil)
}

许可

此库在 Apache 2.0 下获得许可。 完整的许可证文本可在 LICENSE 中找到。