Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

Validate a Google ID Token

See more OAuth2 Examples

Demonstrates how to verify the signature of a Google id token.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    let http = CkoHttp()!

    //  First get the public key we'll be needing..
    var jwkStr: String? = http.quickGetStr(url: "https://www.googleapis.com/oauth2/v3/certs")
    if http.lastMethodSuccess == false {
        print("\(http.lastErrorText!)")
        return
    }

    //  We have the following:

    //      {
    //        "keys": [
    //  	{
    //  	  "kid": "e8732db06287515556213b80acbcfd08cfb302a9",
    //  	  "n": "4RIrO30287Wsq3gqXCMkUYMVAeI3H8...w2mbMNEBQ",
    //  	  "kty": "RSA",
    //  	  "e": "AQAB",
    //  	  "alg": "RS256",
    //  	  "use": "sig"
    //  	},
    //  	{
    //  	  "kid": "8462a71da4f6d611fc0fecf0fc4ba9c37d65e6cd",
    //  	  "e": "AQAB",
    //  	  "n": "xT_ngLZNmT5GBtJZeTB...Ft4gK0eoFi0d3l8bcw",
    //  	  "alg": "RS256",
    //  	  "use": "sig",
    //  	  "kty": "RSA"
    //  	}
    //        ]
    //      }

    let json = CkoJsonObject()!
    success = json.load(json: jwkStr)

    //  -------------------------------------------------

    //  Load the following..

    //   {
    //    "access_token": "ya29.a0...0f",
    //    "expires_in": 3599,
    //    "scope": "openid https://www.googleapis.com/auth/userinfo.email",
    //    "token_type": "Bearer",
    //    "id_token": "eyJhb...o5nQ"
    //  }

    let jsonToken = CkoJsonObject()!
    success = jsonToken.loadFile(path: "qa_data/tokens/google_sample_id_token.json")
    if success == false {
        print("Failed to load the JSON file...")
        return
    }

    //  Get the id_token;
    let sbIdToken = CkoStringBuilder()!
    success = sbIdToken.append(value: jsonToken.string(of: "id_token"))

    //  Get the signature in base64url format.
    //  The header + payload remains in sbIdToken.
    var sig_b64Url: String? = sbIdToken.get(afterFinal: ".", removeFlag: true)
    var headerPlusPayload: String? = sbIdToken.getAsString()

    print("\(sig_b64Url!)")
    print("\(headerPlusPayload!)")

    //  ---------------------------------------------

    //  Try validating with each cert's public key.
    //  Hopefully one will be the key that verifies.

    let rsa = CkoRsa()!
    rsa.encodingMode = "base64url"

    let jsonKey = CkoJsonObject()!
    let pubKey = CkoPublicKey()!

    var numKeys: Int = json.size(ofArray: "keys").intValue
    var i: Int = 0
    while i < numKeys {
        json.i = i

        json.objectOf2(jsonPath: "keys[i]", jsonObj: jsonKey)

        success = pubKey.load(fromString: jsonKey.emit())
        if success == false {
            print("\(pubKey.lastErrorText!)")
            return
        }

        print("\(i)")
        print("\(pubKey.getPem(preferPkcs1: true)!)")

        success = rsa.usePublicKey(pubKey: pubKey)

        var bVerified: Bool = rsa.verifyStringENC(str: headerPlusPayload, hashAlg: "sha256", sig: sig_b64Url)
        print("bVerified = \(bVerified)")

        i = i + 1
    }

    //  The output is:

    //  0
    //  -----BEGIN RSA PUBLIC KEY-----
    //  MIIBCgKCAQEA4RIrO30287Wsq3gqXCMkUYMVAeI3H8LVE6IXR1krdFeGnZLiGUPw
    //  cbkeVpXf3lmJdsStOg+jijces2DZCfPyIBiQuLYfxxmAZE6ErJ0QJFg1stwli2Pz
    //  9ncYhFoqi8pXr7kEzEJBTzX4thuw56ydbGsshSEznPXoerCJOc7UI2+n0wFCWQ4Y
    //  LHbh/PrWt4vdadyUUUW/QpQHXQLdD8q/Qwqdj0O9zlJE7R6Elw2E9EqnHyIGu1hm
    //  LxhqrTru1M18SUhONYbVskV/BCEdVKs//X96849HorWQDCAgVMWfGsdMVq55FAdJ
    //  680N5UmQDRynIZ4+PeNGN4S9iw2mbMNEBQIDAQAB
    //  -----END RSA PUBLIC KEY-----
    //  
    //  bVerified = True
    //  1
    //  -----BEGIN RSA PUBLIC KEY-----
    //  MIIBCgKCAQEAxT/ngLZNmT5GBdkLtJZjNeTB+8B5yWgrq/e5eMZ1hrZhcmLK+dSn
    //  IkpOPV8/OekV67EnQ7I4II2rcNJnHGrGKZziXO3XN2gtUHE+mBJC99oULSbX/QwB
    //  Kz7gC/IBPq9EuxTt6Oq6fPkVQ9DbRIgWJSEGBF/KRaNl3kyAlIZfpY7XgHyJTTv8
    //  E7yAcYKPR+36gzdl+ps0sDLKzUuAtZNq8llK0u80z6AtAUIYwWdkEhM9upy6keKI
    //  TasIxcsO7M6kZPINUSbh6t5VAm8FuqRmxpgg+9c9/GQSGd89InVypoVzWLQ+wOGg
    //  5G4H6JqIgtj0TRFt4gK0eoFi2U0d3l8bcwIDAQAB
    //  -----END RSA PUBLIC KEY-----
    //  
    //  bVerified = False

}