如何创建用于Apple Music的JWT

时间:2017-06-13 06:49:17

标签: ruby jwt

我正在尝试创建一个开发人员令牌,这是一个用于Apple Music身份验证的ES256 JWT。 (Here

我使用ruby和JWT gem但是在创建令牌后,我在使用Apple Music进行身份验证时出现401错误

    require 'jwt'

    payload = {:iss => 'CapExdTeam', :iat => '1497335982', :exp => '1513112982'}

    priv = "-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgU208KCg/doqiSzsVF5sknVtYSgt8/3oiYGbvryIRrzSgCgYIKoZIzj0DAQehRANCAAQfrvDWizEnWAzB2Hx2r/NyvIBO6KGBDL7wkZoKnz4Sm4+1P1dhD9fVEhbsdoq9RKEf8dvzTOZMaC/iLqZFKSN6
-----END PRIVATE KEY-----"
    ecdsa_key = OpenSSL::PKey::EC.new(priv)

    token = JWT.encode payload, ecdsa_key, 'ES256', { :kid => "CapExedKid", :alg => "ES256" }
    puts token

    `curl -v -H 'Authorization: Bearer #{token}' "https://api.music.apple.com/v1/catalog/us/songs/203709340"

我使用示例私钥来模拟429错误仅用于说明目的

4 个答案:

答案 0 :(得分:5)

我使用了这个脚本,它完美无缺 https://github.com/pelauimagineering/apple-music-token-generator

答案 1 :(得分:3)

根据@ DanDevine的回答,这里有更多的Ruby / OO方法:

require "openssl"

# Example: 
#
#  token = AppleMusic::Token.new(key_id: "...", team_id: "...", keyfile: File.new("lib/assets/AuthKey_xxxxxxx.p8"))
#  token.auth_token
#  token.auth_header
# 
module AppleMusic
  class Token
    attr_reader :key_id, :team_id, :keyfile

    # Keyfile should be an IO type that responds to `read`
    def initialize(key_id:, team_id:, keyfile:)
      @key_id = key_id
      @team_id = team_id
      @keyfile = keyfile
    end

    def auth_token
      @auth_token ||= fetch_auth_token
    end

    def auth_header
      "Bearer #{auth_token}"
    end

  protected

    def fetch_auth_token
      header = {
        typ: "JWT", # Must be specified; not in documentation
        alg: "ES256",
        kid: key_id
      }

      body = {
        iss: team_id,
        iat: Time.now.to_i,
        exp: Time.now.to_i + 43_200 # 12hrs
      }

      JWT.encode(body, auth_key, 'ES256', header)
    end

    def auth_key
      key = OpenSSL::PKey::EC.new(keyfile.read)
      key.check_key
      key
    end
  end
end

答案 2 :(得分:1)

这是一个有效的Ruby实现。使用keyId和teamId进行呼叫,提供对私钥文件的访问权限并继续。

class AppleMusic

    @auth_token
    @validity_start
    @validity_end


    def initialize(keyId, teamId, options ={})
      appleKeyId = keyId
      appleTeamId = teamId
      @validity_start = Time.now.to_i
      @validity_end = Time.now.to_i + 43200  # 12 hours in seconds...

      # Build up the headers
      header = {
          'typ' => 'JWT',           # MUST BE SPECIFIED...  Apple doesn't tell you this!
          'alg' => 'ES256',
          'kid' => appleKeyId
      }

      # Build up the payload
      body = {
          'iss' => appleTeamId,
          'iat' => @validity_start,
          'exp' => @validity_end
      }

      # This should be installed manually on the server somewhere
      # TODO:  Add some protection around the file's existance, set the name & location
      # as some type of configuration key.
      file = File.read('lib/assets/AuthKey_xxxxxxx.p8')
      key = OpenSSL::PKey::EC.new(file)
      key.check_key

      @auth_token = JWT.encode(body, key, 'ES256', header)
      @auth_token
    end

    def auth_token
      @auth_token
    end

    def auth_header
      "Bearer #{@auth_token}"
    end

    def validity_start
      @validity_start
    end

    def validity_end
      @validity_end
    end
 end

答案 3 :(得分:0)

现在在纯Swift中也有可能!

您首先必须使用this guide from Apple创建MusicKit标识符和私钥。然后可以使用Swift-JWT from IBM在纯Swift中轻松创建令牌。

或多或少只是对SwiftJWT API的调用:

let teamId = "yourTeamID"
let keyId = "yourKeyID"
let keyFileUrl = URL(fileURLWithPath:"/pathToYour/key.p8")

struct MyClaims: Claims {
    let iss: String
    let iat: Date?
    let exp: Date?
}

let myHeader = Header(kid: keyId)
let myClaims = MyClaims(iss: teamId, iat: Date(), exp: Date() +  24 * 60 * 60)
var myJWT = SwiftJWT.JWT(header: myHeader, claims: myClaims)

let token = try! myJWT.sign(using: .es256(privateKey: try! String(contentsOf: keyFileUrl).data(using: .utf8)!))

我使用Swift软件包管理器创建了一个简单的示例和一个命令行工具:SwiftJWTSample