用于谷歌呼叫apis的{erlang google oauth2协议

时间:2015-11-06 10:31:26

标签: oauth-2.0 google-api erlang jwt erlangweb

您好我正在编写oauth 2库来访问google api,我的代码如下

    jwt_create() ->

    {ok,PemBin} = file:read_file("your-key-file.pem"),
    PemEntry = public_key:pem_decode(PemBin),
    [A,B] = PemEntry,
    io:format("A:: ~p ~n",[A]),
    PrivateKey = public_key:pem_entry_decode(PemEntry),
    JwtHeaderJson = encode_json(jwt_header()),
    JwtClaimsetJson = encode_json(jwt_claimset()),
    ComputeSignature = compute_signature(JwtHeaderJson, JwtClaimsetJson, PrivateKey),
    Z=binary:replace(
      binary:replace(<<JwtHeaderJson/binary, ".", JwtClaimsetJson/binary, ".", ComputeSignature/binary>>,
                     <<"+">>, <<"-">>, [global]),
      <<"/">>, <<"_">>, [global]),
    io:format("JWT:: ~p ~n",[Z]).
compute_signature(Header, ClaimSet,#'RSAPrivateKey'{publicExponent=Exponent

                                                          ,modulus=Modulus

                                                          ,privateExponent=PrivateExponent}) ->
    base64:encode(crypto:sign(rsa, sha256, <<Header/binary, ".", ClaimSet/binary>>, 
            [Exponent, Modulus, PrivateExponent])).
encode_json(JWToken) ->
    base64:encode(jsx:encode(JWToken)).

我收到如下错误:

  

异常错误:没有函数子句匹配                       PUBLIC_KEY:pem_entry_decode([{ 'PrivateKeyInfo进行',&LT;&LT; 48,130,4,191,2,1,0,48,13,6,9,42,134,                                                                        72,134,247,13,1,1,1,5,0,4,130,4,...&GT;&gt;中                                                                      not_encrypted},                                                    { '证书',&LT;&LT; 48,130,3,96,48,130,2,72,160,3,2,1,2,2,8,                                                                     79,59,244,35,60,15,3,155,48,...&GT;&gt;中                                                                   not_encrypted}])(public_key.erl,第123行)        在函数googleoauth:jwt_create / 0(src / googleoauth.erl,第55行)

请帮助我为OAUTH 2生成JWS和JWT以访问google apis

1 个答案:

答案 0 :(得分:1)

您将错误的内容传递给public_key:pem_entry_decode / 1:

这将解决您的问题:

PrivateKey = public_key:pem_entry_decode(A),

public_key:pem_entry_decode / 1只有一个pem_entry()但是PEM文件可以包含很多条目,或许代码PemEntry = public_key:pem_decode(PemBin)应该读取PemEntries = public_key:pem_decode(PemBin)而不是?

另外请注意前面的行假定有两个列表条目,你可能有意思(虽然这里不确定你的意图)?

[A|B] = PemEntry,