APIKeyMiddleware



Minimum Supported Vapor Version is 4

用于为 vapor 后端添加 API 密钥要求的 Swift 包。

特性

用法

请求应具有 api-key 标头。

简单

public func configure(_ app: Application) throws {
    app.middleware.use(APIKeyMiddleware(keys: ["123"]))
}

如果想添加到单个路由,请参阅 Vapor 文档

覆盖错误

默认情况下使用以下错误

要覆盖这些错误,请为 APIKeyMiddleware 分配一个委托。返回 nil 将使用默认值。

class Delegate: APIKeyMiddlewareDelegate {

    static let shared = Delegate()

    init() {}

    func errorForMissingKey(in middleware: APIKeyMiddleware) -> Error? {
        Abort(.imATeapot, reason: "Missing api-key was found by teapot.")
    }

    func errorForUnauthorizedKey(in middleware: APIKeyMiddleware) -> Error? {
        Abort(.imATeapot, reason: "Unauthorized api-key was found by teapot.")
    }
}

public func configure(_ app: Application) throws {
    let middleware = APIKeyMiddleware(keys: ["123"], delegate: Delegate.shared)
    app.middleware.use(middleware)
}

安装

SPM

将以下内容添加到您的项目中

https://github.com/ptrkstr/APIKeyMiddleware

可能的未来特性

如果您需要这些,请提出 issue