Using OAuth v2 to request a SWT token from Windows Azure

Introduction

In my previous post, I used OAuth WRAP to retrieve a SWT token from the service identity. Although OAuth WRAP is still supported in ACS, it would be better to use v2 of the OAuth protocol.
This is because the OAuth WRAP protocol itself has been deprecated somewhere in 2010.
We will take the OAuth WRAP code from the previous post as a starting point.

Prerequisites

The following components are needed in order to complete this walkthrough with a working end to end solution:

  1. Visual Studio 2012
  2. .NET Framework 4.0 and 4.5
  3. The latest Windows Azure tools (In this walkthrough, June 2012 SP1 v1.7.50716.1601 is used)
  4. A Windows Azure account
  5. Windows Identity foundation (For Windows 8 users: you can activate this as a Windows feature in the control pane. Other users can download it here)
  6. The DPE.OAuth project, which is found in the source code attached to this walkthrough
  7. The components that were created in the previous blog post.

Steps

In this walkthrough the following steps are needed:

  1. Change code to retrieve SWT token

Change code to retrieve SWT token

The following code in the AuthenticationHelper class exists (see also my previous blog post):

public static string GetTokenFromAcs(string scope)
        {
            const string wrapPassword = "[Your service identity password]";
            const string wrapUsername = "[Your service identity name here]";

            // request a token from ACS
            var client = new WebClient();
            var address = new Uri("https://[your service namespace here].accesscontrol.windows.net/WRAPv0.9/");

            var values = new NameValueCollection();

            values.Add("wrap_name", wrapUsername);
            values.Add("wrap_password", wrapPassword);
            values.Add("wrap_scope", scope);

            byte[] responseBytes = client.UploadValues(address, "POST", values);

            string response = Encoding.UTF8.GetString(responseBytes);

            string token = response.Split('&').Single(value => value.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase)).Split('=')[1];

            return token;
        }

Replace this by the following code:

public static string GetTokenFromAcs(string scope)
        {
            const string identityName = "[Your service identity name here]";
            const string identityPassword = "[Your service identity password]";

            // Request a token from ACS
            var client = new WebClient();
            var address = new Uri("https://[your service namespace here].accesscontrol.windows.net/v2/OAuth2-13");

            var values = new NameValueCollection();

            values.Add("grant_type", "client_credentials");
            values.Add("client_id", identityName);
            values.Add("client_secret", identityPassword);
            values.Add("scope", scope);

            byte[] responseBytes = client.UploadValues(address, "POST", values);

            string response = Encoding.UTF8.GetString(responseBytes);

            // Parse the JSON response and return the access token
            var serializer = new JavaScriptSerializer();

            var decodedDictionary = serializer.DeserializeObject(response) as Dictionary<string, object>;

            return decodedDictionary["access_token"] as string;
        }

Explanation

Below a summary of the main differences and explanation are given.

  1. The address has been changed to point to /v2/OAuth2-13. This is the endpoint to use when working with OAuth v2 in Windows Azure.
  2. The parameters have been changed in OAuth v2. “wrap-name” and “wrap_password” are renamed to “client_id” and “client_secret” respectively. Furthermore, to specify the type of the access token request, the parameter “grant_type” is used. Finally, “wrap_scope” has been replaced by “scope”. For a more detailed description about the OAuth v2-13 protocol refer to: http://tools.ietf.org/html/draft-ietf-oauth-v2-13.
  3. An OAuth WRAP response is different from an OAuth v2 response as can be seen below.

    OAuth WRAP response example:

    wrap_access_token=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier=ODataClientIdentity
         &http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider=https://mvcodatainthecloud.accesscontrol.windows.net/
         &Audience=http://127.0.0.1/
         &ExpiresOn=1348580052
         &Issuer=https://mvcodatainthecloud.accesscontrol.windows.net/
         &HMACSHA256=E1oyO/ujeYMxmFMy4zOOhUMPF8GMc4riPcSEqNzzq9E=
         &wrap_access_token_expires_in=5999
    

    OAuth v2 response example:

    {
    "token_type":"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0"
    ,"access_token":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier=ODataClientIdentity
         &http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider=https://mvcodatainthecloud.accesscontrol.windows.net/
         &Audience=http://127.0.0.1/
         &ExpiresOn=1348580093
         &Issuer=https://mvcodatainthecloud.accesscontrol.windows.net/
         &HMACSHA256=xN88MLs7D29n7RwnI 3GBa7x8vcjefS6TOL eCGagas="
    ,"expires_in":"5999"
    ,"scope":"http://127.0.0.1/"
    }
    

    As can be seen from this second response example, the format is JSON and can be parsed by a JavaScriptSerializer. The value of the token is stored in the key “access_token”.

Additional notes

If you use the sample code from the previous blog post there is one additional change that has to be done.
Replace the following line in the AddClaimsToToken method (in the AuthenticationHelper class):

int indexOfAudience = token.IndexOf(HttpUtility.UrlEncode("&Audience"), StringComparison.Ordinal);

By the following:

int indexOfAudience = token.IndexOf("&Audience", StringComparison.Ordinal);

Conclusion

Adding support for OAuth v2 in your client application to request a SWT token from Windows Azure does not require a lot of work. Make sure that the right parameters are used corresponding to the type of credentials that are defined for the service identity in the access control service.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s