Coder Social home page Coder Social logo

ethanhuang13 / cupertinojwt Goto Github PK

View Code? Open in Web Editor NEW
141.0 7.0 39.0 56 KB

Parse Apple's .p8 private key file and sign JWT with ES256, without third-party dependencies.

License: MIT License

Swift 91.01% Ruby 4.89% Shell 4.10%
jwt apple es256 swift

cupertinojwt's Introduction

CupertinoJWT

GitHub release GitHub top language License Twitter Donate

Parse Apple's .p8 private key file and sign JWT with ES256, without third-party dependencies. Supports Apple's server-side APIs.

Features

Features
😇 Open source iOS project written in Swift 4
Support iOS, macOS, tvOS, and watchOS
Parse Apple's .p8 private key file
Sign JSON Web Token with ES256 algorithm
Use Security and CommonCrypto only, no third-party dependencies
Support provider token based APNs connection
🏗 Support MusicKit
🏗 Support DeviceCheck
🏗 Support App Store Connect API

Install

CocoaPods

You can use CocoaPods to install CupertinoJWT by adding it to your Podfile:

platform :ios, '10.0'
use_frameworks!

target 'MyApp' do
    pod 'CupertinoJWT'
end

If you see CocoaPods warning about script phase, it is because CupertinoJWT requires CommonCrypto framework. And Apple didn't expose its header for Swift until Xcode 10. We use the script phase to generate module map to use it in Swift.

Carthage

Carthage is a simple, decentralized dependency manager for Cocoa. To install CupertinoJWT with Carthage:

  1. Make sure Carthage is installed.

  2. Update your Cartfile to include the following:

github "ethanhuang13/CupertinoJWT"
  1. Run carthage update and add the appropriate framework.

What's this all about?

Apple has several server APIs uses JSON Web Token(JWT) as authentication method, including Apple Push Notification service (APNs), MusicKit, DeviceCheck and App Store Connect API. Probably more in the future.

After creating the token, one must sign it with an Apple-provided private key, using the Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm, or ES256.

This task is very common and well-supported with mature server-side languages like Ruby, Java, Python, or JS. With Swift, however, is not that easy. One often needs to use OpenSSL or its forks, even server-side Swift frameworks like Vapor or Perfect use OpenSSL forks. If you want to do this on iOS, it's even harder.

Personally I'm interested in creating developer tools running on iOS. For example, we can use the JWT for App Store Connect API on a developer tool app.

Turned out we can just use Apple's Security and CommonCrypto frameworks, and support all Apple platforms. And that's what CupertinoJWT does.

The result is, with CupertinoJWT, we can easily create developer tools on iOS (and also macOS, tvOS, and watchOS) connecting to APNs, App Store Connect, or other Apple server APIs.

What does CupertinoJWT do?

The private keys provided by Apple are PEM format .p8 files. CupertinoJWT parses and convert them to ASN.1 data, retrieve the private keys, loads with SecKeyCreateWithData method, and finally create signature using SecKeyCreateSignature method.

Usage

First, get your .p8 key file from Apple Developer site. It can be download once. Keep the file safe. (As a developer, you should know the importance for keeping the private keys safe.)

Then, follow the sample code below:

// Get content of the .p8 file
let p8 = """
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgGH2MylyZjjRdauTk
xxXW6p8VSHqIeVRRKSJPg1xn6+KgCgYIKoZIzj0DAQehRANCAAS/mNzQ7aBbIBr3
DiHiJGIDEzi6+q3mmyhH6ZWQWFdFei2qgdyM1V6qtRPVq+yHBNSBebbR4noE/IYO
hMdWYrKn
-----END PRIVATE KEY-----
"""

// Assign developer information and token expiration setting
let jwt = JWT(keyID: keyID, teamID: teamID, issueDate: Date(), expireDuration: 60 * 60)

do {
    let token = try jwt.sign(with: p8)
    // 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")
} catch {
    // Handle error
}

Contribution

  • Feedback and issues are welcome.
  • Submit each pull request for single purpose. Here is a great article about making code review easier.

Special Thanks

cupertinojwt's People

Contributors

ethanhuang13 avatar janc avatar jogu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

cupertinojwt's Issues

Possible bug in the ASN.1 to raw signature conversion

I think I found a bug in your ASN.1 parsing logic while I was working on an open issue in the JOSESwift project.

The raw signatures need to have a fixed length, so that the recipient can know where the value of R ends and the value of S begins. In the ASN.1 format this length can vary, since the length of the numbers is explicitly encoded.

Basically this means the integers inside the ASN.1 structure can sometimes be shorter than the fixed length they need to have in the raw signature format. On the rare occasions when this happens the signature validation will fail.

I think you should be able to reproduce this issue by generating and verifying something like 10k signatures using the raw format. Some of the verifications should fail because of this issue.

I was only working and testing with the ASN1.swift file and not with your full project, so I am not submitting a PR right now, but this is the fix that worked for me in that context:

I replaced your calls to

private func dropLeadingBytes() -> Data {
    if self.count == 33 {
        return self.dropFirst()
    }
    return self
}

with calls to

private func fixOctetLength(octetLength: Int) -> Data {
    if self.count == octetLength + 1 {
        return self.dropFirst()
    }
    if self.count < octetLength {
        return Data.init(count: octetLength - self.count) + self;
    }
    return self
}

which also pads R and S if they are too short.

Linux support

I need to create MusicKit tokens on Linux (through Vapor). Is there any chance this library supports Linux?

Can't verify ES256 signed token on jwt.io

Hi,

I'm try to use CupertinoJWT to generate an ES256 signed jwt that's NOT for use with Apple services. It seems to work nicely except I just can't get the signature to verify, I wonder if you have any ideas?

I'm using the example you give:

       // Get content of the .p8 file
        let p8 = """
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgGH2MylyZjjRdauTk
xxXW6p8VSHqIeVRRKSJPg1xn6+KgCgYIKoZIzj0DAQehRANCAAS/mNzQ7aBbIBr3
DiHiJGIDEzi6+q3mmyhH6ZWQWFdFei2qgdyM1V6qtRPVq+yHBNSBebbR4noE/IYO
hMdWYrKn
-----END PRIVATE KEY-----
"""

        // Assign developer information and token expiration setting
        let jwt = JWT(keyID: "moo", teamID: "bar", issueDate: Date(), expireDuration: 60 * 60)

        do {
            let token = try jwt.sign(with: p8)
            // 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("signed jwt:\n\(token)")
        } catch {
            // Handle error
        }

Which gives a token:

eyJhbGciOiJFUzI1NiIsImtpZCI6Im1vbyJ9.eyJpc3NYWCI6ImJhcjIiLCJpYXQiOjE1MzcwOTg0MzIsImV4cCI6MTUzNzEwMjAzMn0.MEQCIES1_Ry1Ia-l0bkOcHGQ6OSPPocvXShOCtTVo4Y4hMBDAiBRLLhebK3YoyuJ46iJpohKZgfs24E5ARp1YAFnDPu-rg
(NB: I made a trivial mod to stop CupertinoJWT including 'iss', as I was seeing errors in the js console on jwt.io related to the iss value that I wanted to rule out as a cause of the problem.)

I get the public key using:

openssl ec -in private-key.pem -pubout -out pubkey.pem

which gives:

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEv5jc0O2gWyAa9w4h4iRiAxM4uvqt
5psoR+mVkFhXRXotqoHcjNVeqrUT1avshwTUgXm20eJ6BPyGDoTHVmKypw==
-----END PUBLIC KEY-----

and then I try and verify using jwt.io, but it fails the signature validation. (I'm not including the jwt.io shareable url as I find these show 'invalid signature' even when viewing with a valid object - I've just reported a bug about that in their GitHub. Pasting things into jwt.io appears to work correctly, it's just the pre-filled out urls that don't seem to work.)

I tried getting JWT.io to sign (using the same private key), and that gives this jwt, which jwt.io can verify using the public key above:

eyJhbGciOiJFUzI1NiIsImtpZCI6Im1vbyJ9.eyJpYWFhYWFhdCI6MTUzNzA5MzQ5NywiZXhlZWVlcCI6MTUzNzA5NzA5N30.fsvs3UD6zTMWvrQDqXJxzTUfanCO5ZFwRM-NeZuTJx8ICR2Hkn8K9_xzaISxHYV0jXCyuKOc5VJBUsprpMARig

One difference I noticed is that the signature jwt.io produces is 86 bytes base64 encoded (64 bytes decoded), whereas the one from Cupertino.jwt is 94 bytes of base64, decoding to 70 bytes.

The example in https://tools.ietf.org/html/rfc7515#appendix-A.3.1 is 64 bytes decoded. Unless I have really misunderstood something, I believe CupertinoJWT is intended to output standard ES256, so I would have expected it to also be generating a 64 byte signature.

The CupertinoJWT generated signatures also seem to always being 'ME'; this makes me suspicious that there may be a header of some kind before the actual signature.

(Testing done on an iPad running iOS 11.4.1, using an app built using Xcode 10 GM.)

Always get 401 for Apple Music

I've done everything as stated to generate my JWT:

let p8 = """REMOVED"""

        // Assign developer information and token expiration setting
        let jwt = JWT(
            keyID: "REMOVED",
            teamID: "REMOVED,
            issueDate: Date(),
            expireDuration: 60 * 60
        )

It gives me this token:

eyJhbGciOiJFUzI1NiIsImtpZCI6Ilg0MkNYVzQ5RFIifQ.eyJpc3MiOiJXNjlEQjQ3NFM5IiwiaWF0IjoxNTU5OTA2NzIzLCJleHAiOjE1NTk5MTAzMjN9._cY_IDynpOgjg7TptcZuIBpUTvxNw1CdmixMlFZe5OU9Q_0HIiyQvyPyZb1sfFXuzDx0VqvqqBvBJrGQvAwTtw

I'm then using it in a request like this:

curl -v -H 'Authorization: Bearer eyJhbGciOiJFUzI1NiIsImtpZCI6Ilg0MkNYVzQ5RFIifQ.eyJpc3MiOiJXNjlEQjQ3NFM5IiwiaWF0IjoxNTU5OTA2NzIzLCJleHAiOjE1NTk5MTAzMjN9._cY_IDynpOgjg7TptcZuIBpUTvxNw1CdmixMlFZe5OU9Q_0HIiyQvyPyZb1sfFXuzDx0VqvqqBvBJrGQvAwTtw' "https://api.music.apple.com/v1/catalog/us/songs/203709340"

But it's just returning a 401 each time. Why?! (These are my real values, I'll generate another Music Kit Key for privacy reasons if I can solve this).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.