Skip to content

Commit

Permalink
update to jwt-kit v5beta
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaap Wijnen committed Oct 22, 2024
1 parent 927b20c commit e8cdcf3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 25 deletions.
2 changes: 1 addition & 1 deletion Core/Sources/Configuration/OAuth/OAuthPayload.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public struct OAuthPayload: JWTPayload {
/// Using to nominate the account you want access to on the domain from a service account
var sub: String?

public func verify(using signer: JWTSigner) throws {
public func verify(using algorithm: any JWTAlgorithm) async throws {
try exp.verifyNotExpired()
}
}
50 changes: 27 additions & 23 deletions Core/Sources/Configuration/OAuth/OAuthServiceAccount.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,40 +31,44 @@ public class OAuthServiceAccount: OAuthRefreshable {

// Google Documentation for this approach: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
public func refresh() -> EventLoopFuture<OAuthAccessToken> {
do {
let headers: HTTPHeaders = ["Content-Type": "application/x-www-form-urlencoded"]
let token = try generateJWT()
let headers: HTTPHeaders = ["Content-Type": "application/x-www-form-urlencoded"]

return generateJWT(on: self.eventLoop).flatMapThrowing { (token: String) -> HTTPClient.Request in
let body: HTTPClient.Body = .string("grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=\(token)"
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
let request = try HTTPClient.Request(url: GoogleOAuthTokenUrl, method: .POST, headers: headers, body: body)
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")

return httpClient.execute(request: request, eventLoop: .delegate(on: self.eventLoop)).flatMap { response in

guard var byteBuffer = response.body,
let responseData = byteBuffer.readData(length: byteBuffer.readableBytes),
response.status == .ok else {
return self.eventLoop.makeFailedFuture(OauthRefreshError.noResponse(response.status))
}

do {
return self.eventLoop.makeSucceededFuture(try self.decoder.decode(OAuthAccessToken.self, from: responseData))
} catch {
return self.eventLoop.makeFailedFuture(error)
}
return try HTTPClient.Request(url: GoogleOAuthTokenUrl, method: .POST, headers: headers, body: body)
}.flatMap { request in
return self.httpClient.execute(request: request, eventLoop: .delegate(on: self.eventLoop))
}.flatMap { (response: HTTPClient.Response) in
guard var byteBuffer = response.body,
let responseData = byteBuffer.readData(length: byteBuffer.readableBytes),
response.status == .ok else {
return self.eventLoop.makeFailedFuture(OauthRefreshError.noResponse(response.status))
}

} catch {
return self.eventLoop.makeFailedFuture(error)
do {
return self.eventLoop.makeSucceededFuture(try self.decoder.decode(OAuthAccessToken.self, from: responseData))
} catch {
return self.eventLoop.makeFailedFuture(error)
}
}
}

private func generateJWT() throws -> String {
private func generateJWT(on eventLoop: EventLoop) -> EventLoopFuture<String> {
let payload = OAuthPayload(iss: IssuerClaim(value: credentials.clientEmail),
scope: scope,
aud: AudienceClaim(value: GoogleOAuthTokenAudience),
exp: ExpirationClaim(value: Date().addingTimeInterval(3600)),
iat: IssuedAtClaim(value: Date()), sub: subscription)
let privateKey = try RSAKey.private(pem: credentials.privateKey.data(using: .utf8, allowLossyConversion: true) ?? Data())
return try JWTSigner.rs256(key: privateKey).sign(payload)

let privateKey: Insecure.RSA.PrivateKey
do {
privateKey = try Insecure.RSA.PrivateKey(pem: credentials.privateKey.data(using: .utf8, allowLossyConversion: true) ?? Data())
} catch {
return eventLoop.makeFailedFuture(error)
}

return eventLoop.makeFutureWithTask { try await JWTKeyCollection().addRS256(key: privateKey).sign(payload) }
}
}
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.18.0"),
.package(url: "https://github.com/vapor/jwt-kit.git", from: "4.13.0")
.package(url: "https://github.com/vapor/jwt-kit.git", from: "5.0.0-beta.1")
],
targets: [
.target(
Expand Down

0 comments on commit e8cdcf3

Please sign in to comment.