Monday, March 10, 2014

Generating Password based OAuth Access Token In Response Flow

At times, it's required to generate access token in response flow based some custom validation performed with the backend API. In my scenario, I needed refresh token to be generated too. So I could not use implicit OAuth token generation. The best option in my case was to use password based access token generation.

Consider the following oauth policy to generate password based access token.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<OAuthV2 enabled="true" continueOnError="false" async="false" name="generateAccessToken">
    <Operation>GenerateAccessToken</Operation>
    <AppEndUser>Srikanth</AppEndUser>
    <UserName>sriki</UserName>
    <PassWord>sriki</PassWord>
    <GrantType>grant_type</GrantType>
    <ClientId>sriki_client_id</ClientId>
    <SupportedGrantTypes>
        <GrantType>password</GrantType>
    </SupportedGrantTypes>
</OAuthV2>

Above policy continued to fail with 401 UnAuthorized error even though I had specified correct parameters. The solution for such a scenario (found on discussions with internal experts) is the need for an Authorization request header.

The Authorization header should contain Basic Base64-encoded (clientid:client secret). Following Javascript policy step prior to OAuth access token generation will solve the issue.

var client_id = context.getVariable("local_clientid");
var client_secret = context.getVariable("local_secret");
context.setVariable("request.header.Authorization","Basic "+CryptoJS.enc.Base64.stringify(CryptoJS.enc.Latin1
                                      .parse(client_id + ':' + client_secret)));


No comments:

Post a Comment