Building42 / Telegraph

Secure Web Server for iOS, tvOS and macOS

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Basic Auth/OAuth (Authorization header) Support?

pansophy opened this issue · comments

Is there a way to add basic auth or OAuth support like CocoaHTTPServer?

@pansophy It should be possible to add these types of authorization. The web server aspect of authorization often involves headers and redirection, both are possible with Telegraph.

For example you can specify a Authorization header like this:

request.headers.authorization = "Bearer 0b79bab50daca910b000d4f1a2b675d604257e42"

And then read that header in the handler of your route:

  /// Handles the authorization request.
  private func serverHandleAuth(request: HTTPRequest) -> HTTPResponse {
    guard validateAuthorization(request.headers.authorization) else {
      return HTTPResponse(.forbidden)
    }

    return HTTPResponse(content: "Welcome, you have access!")
  }

  /// Validates the authorization header and the token it carries.
  private func validateAuthorization(_ authorization: String?) -> Bool {
    guard let authorization = authorization else { return false }

    // The authorization should look like: Bearer <token>
    let parts = authorization.split(separator: " ")
    guard parts.count == 2, parts[0] == "Bearer" else { return false }

    // The token should be valid (add your own business logic here)
    let token = parts[1]
    guard token.count == 40 else { return false }
    guard token.hasPrefix("0b"), token.hasSuffix("42") else { return false }

    return true
  }