Skip to content

Instantly share code, notes, and snippets.

@wdshin
Created December 4, 2014 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wdshin/2eb6998913b3b95454bc to your computer and use it in GitHub Desktop.
Save wdshin/2eb6998913b3b95454bc to your computer and use it in GitHub Desktop.
google oauth2
%%%-------------------------------------------------------------------
%%% @author 신원동 <wodshin@gmail.coml>
%%% @copyright (C) 2014, 신원동
%%% @doc
%%%
%%% @end
%%% Created : 4 Dec 2014 by 신원동 <wodshin@gmail.com>
%%%-------------------------------------------------------------------
-module(m_oauth2).
-include_lib("public_key/include/public_key.hrl").
%% API
-export([access_token/3]).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% @spec
%% @end
%%--------------------------------------------------------------------
access_token(ISS,Scope,PemFileName) ->
Payload = jwt(ISS,Scope,PemFileName),
Headers=[ {"Content-type", "application/x-www-form-urlencoded" } ],
{ RetCode , OpCode, Json , Attachment } = ibrowse:send_req("https://accounts.google.com/o/oauth2/token", Headers , post, Payload , [] ),
case { RetCode , OpCode } of
{ ok , "200" } ->
R = jsx:decode(list_to_binary(Attachment)),
Token = proplists:get_value(<<"access_token">>,R,<<"">>),
{ ok , Token };
_ ->
{ error , OpCode }
end.
%%%===================================================================
%%% Internal functions
%%%===================================================================
jwt_header() ->
<<"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9">>.
aud() ->
<<"https://accounts.google.com/o/oauth2/token">>.
exp(IAT) ->
IAT + 60*60.
iat() ->
m_util_time:epoch().
jwt_claim_set(ISS,Scope) ->
IAT = iat(),
EXP = exp(IAT),
R = [ { <<"iss">> , ISS } , { <<"scope">> , Scope } , { <<"aud">> , aud() } , { <<"exp">> , EXP } , { <<"iat">> , IAT } ],
Bin = jsx:encode(R),
base64url:encode(Bin).
get_private_key(PemFileName) ->
{ ok , F } = file:read_file(PemFileName),
PrivateKeyEntry = public_key:pem_decode(F),
PrivateKeyEntry1=hd(PrivateKeyEntry),
PrivateKey = public_key:pem_entry_decode(PrivateKeyEntry1),
#'RSAPrivateKey'{publicExponent=Exponent
,modulus=Modulus
,privateExponent=PrivateExponent} = PrivateKey,
[Exponent, Modulus, PrivateExponent].
jwt(ISS,Scope,PemFileName) ->
ToEncrypt = << (jwt_header())/binary , $. , (jwt_claim_set(ISS,Scope))/binary >>,
Key = get_private_key(PemFileName),
S=base64url:encode(crypto:sign(rsa,'sha256',ToEncrypt,Key)),
<< <<"grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=">>/binary , ToEncrypt/binary , $. , S/binary >>.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment