在 swift 中为 DeviceCheck API 生成授权持有者令牌时遇到问题

Facing issue while generating Authorization bearer token for DeviceCheck API in swift

我正在研究 DeviceCheck。要生成 JSON 网络令牌,我正在使用 SwiftJWT 库。但我不知道如何为 DeviceCheck.

生成 JWT

代码:

let contents = try String(contentsOfFile: filepath)
let headers = Header(kid: key_id)

struct MyClaims: Claims {
    var iss: String
    var iat: Date
    var exp: Date
}

let jwt = JWT(header: headers, claims: MyClaims(iss: iss_id, iat: Date(timeIntervalSinceNow: 3600), exp: Date(timeIntervalSinceNow: 3600)))
let privateKey = contents.data(using: .utf8)!
let rsaJWTEncoder = JWTEncoder(jwtSigner: JWTSigner.es256(privateKey: privateKey))

var jwtString =  try rsaJWTEncoder.encodeToString(jwt)

在打印时 JWT 我收到以下响应:

JWT(header: SwiftJWT.Header(typ: Optional("JWT"), alg: Optional("ES256"), jku: nil, jwk: nil, kid: Optional("KEY_ID"), x5u: nil, x5c: nil, x5t: nil, x5tS256: nil, cty: nil, crit: nil), claims: SwiftiOSDeviceCheck.ViewController.(unknown context at 4614dbc).(unknown context at 4614e28).MyClaims(iss: "ISS_ID", iat: 2019-06-03 11:55:53 +0000, exp: 2019-06-03 11:55:53 +0000))

并且来自 API 我在邮递员中收到以下回复:

无法验证授权令牌

我该如何解决这个问题?

我找到了这个问题的答案。我使用 CupertinoJWS 而不是 SwiftJWT.

let jwt = JWT(keyID: keyID, teamID: teamID, issueDate: Date(), expireDuration: 60 * 60)

    do {
        let token = try jwt.sign(with: p8Key)
        // Use the token in the authorization header in your requests connecting to Apple’s API server.
        // e.g. urlRequest.addValue(_ value: "bearer \(token)", forHTTPHeaderField field: "authorization")
        print("Generated JWT: \(token)")
        return token
    } catch {
        // Handle error
    }