Getting SWT token from ACS 2.0

Damir Dobric Posts

Next talks:



Follow me on Twitter: #ddobric




Following HTTP request shows how to request the token from ACS 2.0. (Note: the content is obfuscated!)

POST /v2/OAuth2-13 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 201
Expect: 100-continue
Connection: Keep-Alive

grant_type=client_credentials&client_id=ManagementClient&client_secret=FhRX. . .d&

This request can be created by following method:

        static string GetSWTTokenFromACSv2()
            WebClient client = new WebClient();
            client.BaseAddress = string.Format(CultureInfo.CurrentCulture,
             "https://{0}.{1}", SamplesConfiguration.ServiceNamespace, SamplesConfiguration.AcsHostUrl);

            NameValueCollection values = new NameValueCollection();
            values.Add("grant_type", "client_credentials");
            values.Add("client_id", SamplesConfiguration.ManagementServiceIdentityName);
            values.Add("client_secret", SamplesConfiguration.ManagementServiceIdentityKey);
            values.Add("scope", client.BaseAddress + SamplesConfiguration.AcsManagementServicesRelativeUrl);

            byte[] responseBytes = client.UploadValues("/v2/OAuth2-13", "POST", values);

            // Extract the access token and return it.
            using( MemoryStream responseStream = new MemoryStream(responseBytes))
                string token = “Bearer ” + new DataContractJsonSerializer(typeof(OAuth2TokenResponse)).ReadObject(responseStream);
return token;

The request shown above requests the OAuth2-13 token which can be used for management functionalities of ACS. For example, this is useful when you write a application to manage identities or any other ACSv2  artifacts. The result of this request is:(Note: the content is obfuscated!)

HTTP/1.1 200 OK
Cache-Control: public, no-store, max-age=0
Content-Type: application/json; charset=us-ascii
Expires: Mon, 25 Apr 2011 07:48:03 GMT
Last-Modified: Mon, 25 Apr 2011 07:48:03 GMT
Vary: *
Server: Microsoft-IIS/7.0
Set-Cookie: ASP.NET_SessionId=1aaefbzy1rsejr45tyypkj55; path=/; HttpOnly
X-AspNetMvc-Version: 2.0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Mon, 25 Apr 2011 07:48:03 GMT
Content-Length: 666



At the end we need to deserialize the JSON formatted token and append it to the header of next request which requires the token:

String token =  "Bearer  “ + new DataContractJsonSerializer(typeof(OAuth2TokenResponse)).ReadObject(responseStream)

HttpWebRequest request = …

reequest.Headers.Add(HttpRequestHeader.Authorization, token);


Posted Apr 25 2011, 11:16 AM by Damir Dobric


Judy wrote re: Getting SWT token from ACS 2.0
on 10-04-2011 1:36

Your answer was just what I nedeed. It's made my day! is a .Net Community Blog powered by daenet GmbH.