Server-side scenarios

77 out of 101 rated this helpful - Rate this topic

Although client-side code works in many scenarios, there might be some in which you can't or don't want to use it or the Live Connect JavaScript API to access Live Connect services. Some examples of when you might prefer to access Live Connect services from your web server include when you want to:

  • Keep track of user sessions that use Live Connect.
  • Connect the user's Microsoft account to your own website's credential system.
  • Have your web server access users' info on their behalf when they are not online.

To access Live Connect services from your web server, you can use the Representational State Transfer (REST) API or the Live Connect SDK for ASP.NET in server-side scripts.

To write scripts that exercise Live Connect server-side scenarios, you typically do the following:

  1. Prompt the user to sign in to Live Connect and to consent to the scopes that you have requested.
  2. If the user successfully signs in and consents, capture the authorization code that the Live Connect authorization web service returns to you.
  3. Use the authorization code to call the Live Connect authorization web service to obtain an access token—and a refresh token, if the user consented to the wl.offline_access scope. (You also get an authentication token, which is useful for single sign-on scenarios. For more info, see Single sign-on for apps and websites.)
  4. Use the access token to call the Live Connect REST API to work with the user's info, depending on the scopes for which consent has been granted. Repeat this step as needed until the Live Connect REST API indicates that the access token has expired.
    1. If the access token has expired, use the refresh token (if you have one) to obtain a new access token, and then go back to the beginning of step 4.
    2. If the refresh token has also expired, go back to step 1.

The sections in this topic describe this process in more detail.

Getting an authorization code

The first step to obtain an access token and an authorization token—and a refresh token, if the user consented to a wl.offline_access scope request—is to obtain an authorization code. In a later step, you exchange this authorization code for an access token and an authorization token, and optionally a refresh token.

Retain the authorization code for use in the next section, Getting tokens.

Using the REST API to get an authorization code

To obtain an authorization code, direct the user to the Live Connect OAuth 2.0 endpoint by using the following URL. But first replace the following elements in the URL:

  • Replace CLIENT_ID with your app's client ID.
  • Replace SCOPES with the scopes that you want the user to give you permission to access. Separate each requested scope with the URL escape code %20.

    Note  If you want to obtain a refresh token in addition to an access token, you must also include the wl.offline_access scope in the scope query parameter. (A refresh token enables you to obtain a replacement access token to interact directly with the Live Connect REST API on behalf of a user, after the user ends his or her web browsing session.)

  • Replace REDIRECT_URI with the Uniform Resource Identifier (URI) of your callback webpage. The callback URI must use URL escape codes, such as %20 for spaces, %3A for colons, and %2F for forward slashes.
https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=SCOPES&response_type=code&redirect_uri=REDIRECT_URI

For example, the following URL uses a client ID of 0000000603DB0F, the wl.signin and wl.basic scopes, and a redirect URI of http://www.contoso.com/callback.php.

https://login.live.com/oauth20_authorize.srf?client_id=0000000603DB0F&scope=wl.signin%20wl.basic&response_type=code&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.php

Note  Optionally, you can also append the following query parameters to the preceding URL:

  • A display query parameter, which represents a request for the display mode of the consent page, can be set to popup, touch, or none.
  • A locale query parameter, which is used by the request for consent page to display localized UI text in the user's preferred language. This query parameter can be set to a market value, such as en. For details, see Supported locales.
  • A state query parameter, which represents any arbitrary text string that you may want to pass to the redirect URL for your own use.

When the URL is called from a webpage, the Live Connect authorization web service checks to determine whether there is a signed-in user. If the user is not signed in, he or she is prompted to sign in to Live Connect. After the user signs in, the Live Connect authorization web service checks to see whether the user previously consented to the requested scopes. If the user has not consented previously, he or she is prompted to consent to the requested scopes. If the user consents, the Live Connect authorization web service sends the authorization code to the redirect URI, with the authorization code appended as a query parameter named code, as shown in the following example.

http://www.contoso.com/callback.php?code=2bd12503-7e88-bfe7-c5c7-82274a740ff

Using the Live Connect SDK for ASP.NET to get an authorization code

This example shows how you can construct the URL if you are using the Live Connect SDK for ASP.NET.


LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, null);
string[] scopes = new string[] { "wl.signin", "wl.basic"};
string loginUrl = liveAuthClient.GetLoginUrl(scopes, "http://www.contoso.com/callback");


Top

Getting tokens

After you have obtained an authorization code, you exchange it for an access token and an authorization token—and a refresh token, if the user consented to a wl.offline_access scope request.

The following sections show how to use the Live Connect APIs to obtain the tokens. If you add wl.offline_access to the list of requested scopes in the following examples, and the user consents to your request, the Live Connect authorization web service sends to the callback URI an access token, an authentication token, and a refresh token. These tokens are represented as strings of characters, in the access_token, authentication_token, and refresh_token key/value pairs, inside a JavaScript Object Notation (JSON)-formatted object, as shown in the following example.

{
    "token_type":"bearer",   
    "expires_in":3600,
    "scope":"wl.offline_access wl.signin wl.basic",
    "access_token":"EwCo...//access token string shortened for example//...AA==",
    "refresh_token":"*LA9...//refresh token string shorted for example//...k%65",
    "authentication_token":"eyJh...//authentication token string shortened for example//...93G4"
}

Note  A typical refresh token string consists of well over 200 characters, so part of the refresh token string is omitted for brevity in the preceding example.

Retain this access token (and the refresh token, if you obtained one) for use in the following sections.

Note  To use an authentication token, which is useful for single sign-on scenarios, see Single sign-on for apps and websites.

Using the REST API to get tokens

To obtain an access token and an authorization token (and, optionally, a refresh token), make an HTTP POST call to the Live Connect authorization web service by using the following URL.

https://login.live.com/oauth20_token.srf

The Content-Type header should have the value "application/x-www-form-urlencoded". Construct the request body as shown in the following example, and replace these elements:

  • Replace CLIENT_ID with your app's client ID.
  • Replace REDIRECT_URI with the URI to your callback webpage. This URI must be the same as the URI that you specified when you requested an authorization code. The URI must use URL escape codes, such as %20 for spaces, %3A for colons, and %2F for forward slashes.
  • Replace CLIENT_SECRET with your app's client secret. The client secret must use URL escape codes, such as %2B for the plus sign.
  • Replace AUTHORIZATION_CODE with the authorization code that you obtained earlier.
client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&client_secret=CLIENT_SECRET&code=AUTHORIZATION_CODE&grant_type=authorization_code

For example, the following request body uses a client ID of 0000000603DB0F, a redirect URI of http://www.contoso.com/callback.php, a client secret of LWILlT555GicSrIATma5qgyBXebRI, and an authorization code of 2bd12503-7e88-bfe7-c5c7-82274a740ff.

client_id=0000000603DB0F&redirect_uri=http://www.contoso.com/callback.php&client_secret=LWILlT555GicSrIATma5qgyBXebRI&code=2bd12503-7e88-bfe7-c5c7-82274a740ff&grant_type=authorization_code

If the call is successful, the response for the HTTP POST request contains an access token and an authentication token. These tokens are each represented as a string of characters, in an access_token and an authentication_token key/value pair inside a JSON-formatted object, as shown in the following example.

{
    "token_type":"bearer"
    "expires_in":3600,
    "scope":"wl.signin wl.basic",
    "access_token":"EwCo...//access token string shortened for example//...AA==",
    "authentication_token":"eyJh...//authentication token string shortened for example//...93G4"
}

Note   A typical token string consists of well over 550 characters, so part of each token string is omitted for brevity in the preceding example.

Using the Live Connect SDK for ASP.NET to get tokens

This example shows how to get the tokens if you are using the Live Connect SDK for ASP.NET.


private LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, null);
private LiveConnectSession session = null;

private async Task HandleAuthorizationAsync()
{
    try
    {
        LiveLoginResult result = await liveClient.ExchangeAuthCodeAsync(this.HttpContext);
        session = result.Session;
    }
    catch (LiveAuthException)
    {
    }
}


Task HandleAuthorizationAsync invokes LiveAuthClient.ExchangeAuthCodeAsync, which reads the authorization server’s response from the Http request. The server’s response can be either an authorization code or an error message. If the response is an authorization code, it retrieves the access token, authentication token, and refresh token from the authorization server. LiveAuthClient.ExchangeAuthCodeAsync returns an instance of LiveLoginResult, which has a Session property of the LiveConnectSession type. If the session is available, the Session property contains all the server response detail described in the earlier REST example.

Top

Using an access token to work with a user's info

After you have obtained an access token, you can use it to work with the consenting user's info.

Using the REST API to work with a user's info

To make an HTTP GET call to the Live Connect REST API to get user info, use the following URL and replace these placeholders:

  • Replace REST_PATH with the REST path to the portion of the user's info that you want—for example, me.
  • Replace ACCESS_TOKEN with your access token.
https://apis.live.net/v5.0/REST_PATH?access_token=ACCESS_TOKEN

For example, the following URL uses a REST path of me, and an access token that starts with the characters "EwCo" and ends with the characters "AA==".

https://apis.live.net/v5.0/me?access_token=EwCo...//access token string shortened for example//...AA==

If the HTTP GET call is successful, the Live Connect REST API sends the requested info as a JSON-formatted object or collection, depending on the shape of the info, as shown in the following example.

{
   "id": "b6b2a7e8f2515e5", 
   "name": "Apurva Dalia", 
   "first_name": "Apurva", 
   "last_name": "Dalia", 
   "gender": null, 
   "link": "http://cid-b6b2a7e8f2515e5.profile.live.com/", 
   "locale": "en_US", 
   "updated_time": "2011-10-26T21:13:05+0000"
}

Using the Live Connect SDK for ASP.NET to work with a user's info

This example shows how to work with a user's info if you are using the Live Connect SDK for ASP.NET.


public async Task<ActionResult> Index()
{
    try
    {
        LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, RedirectURL);
        LiveLoginResult result = await liveAuthClient.ExchangeAuthCodeAsync(this.HttpContext);
        if (result.Status == LiveConnectSessionStatus.Connected)
        {
            LiveConnectClient client = new LiveConnectClient(this.MSAuthClient.Session);
            LiveOperationResult meResult = await client.GetAsync("me");
            if (meResult != null)
            {
                dynamic meInfo = meResult.Result;
                this.SetNameField(meInfo.name);
            }
        }
    }
    catch (LiveAuthException authEx)
    {
        // Handle auth errors.
    }
    catch (LiveConnectException connectEx)
    {
        // Handle connect errors.
    }

    ...

    return View();
}


Top

Using a refresh token to get a new access token and a new refresh token

If you have obtained a refresh token and the access token has expired, you can obtain a replacement access token and a replacement refresh token.

Using the REST API to get a new access token and a new refresh token

To obtain replacement tokens, make an HTTP POST call to the Live Connect authorization web service at the following URL.

https://login.live.com/oauth20_token.srf

The Content-Type header should have the value "application/x-www-form-urlencoded". Construct the request body using the following template and replace these elements:

  • Replace CLIENT_ID with your app's client ID.
  • Replace REDIRECT_URI with the URI to your callback webpage. This URI must be the same as the URI that you specified when you requested an authorization code. The URI must use URL escape codes, such as %20 for spaces, %3A for colons, and %2F for forward slashes.
  • Replace CLIENT_SECRET with your app's client secret. The client secret must use URL escape codes, such as %2B for the plus sign.
  • Replace REFRESH_TOKEN with the refresh token that you obtained earlier.
client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&client_secret=CLIENT_SECRET&refresh_token=REFRESH_TOKEN&grant_type=refresh_token

For example, the following request body uses a client ID of 0000000603DB0F, a redirect URI of http://www.contoso.com/callback.php, a client secret of LWILlT555GicSrIATma5qgyBXebRI, and a refresh token that starts with "*LA9" and that ends with "xRoX".

client_id=0000000603DB0F&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.php&client_secret=LWILlT555GicSrIATma5qgyBXebRI&refresh_token=*LA9...//refresh token string shortened for example//...xRoX&grant_type=refresh_token

If the call is successful, the Live Connect authorization web service sends to the callback URI a replacement access token and a replacement refresh token. These tokens are represented as strings of characters, in the access_token and refresh_token key/value pairs, inside a JSON-formatted object, as shown in the following example.

{
    "token_type":"bearer",
    "expires_in": 3600,
    "scope": "wl.offline_access wl.signin wl.basic",
    "access_token":"FxDp...//access token string shortened for example//...BB==",
    "refresh_token":"Cla*...//refresh token string shorted for example//...pdeA",
    "authentication_token":"eyJh...//authentication token string shortened for example//...UWJE"
}

Using the Live Connect SDK for ASP.NET to get a new access token and a new refresh token

This example shows how to get a new access token and a new refresh token if you are using the Live Connect SDK for ASP.NET.


public class AccountController : Controller, IRefreshTokenHandler
{
    Task IRefreshTokenHandler.SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo)
    {
        await SaveRefreshTokenToDBForCurrentUserAsync(tokenInfo);
    }

    Task<RefreshTokenInfo> IRefreshTokenHandler.RetrieveRefreshTokenAsync()
    {
        return await RetrieveRefreshTokenFromDBForCurrentUserAsync();
    }

    public async Task<ActionResult> Refresh()
    {
        try
        {
             LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, RedirectURL, this);
             LiveLoginResult result = await liveAuthClient.InitializeSessionAsync(this.HttpContext);
             session = result.Session;
        }
        catch (LiveAuthException)
        {
        }

        return View();
    }
}


Note  

  • A refresh token is available if the sign-in URL includes the scope wl.offline_access.
  • The AccountController class implements the IRefreshHandler to handle refresh-token persistency.
  • The refresh token should be associated with the user ID in your app credential system.
  • IntializeSessionAsync retrieves a new access token using an available refresh token if the current session does not have a valid access token. The method will invoke the IRefreshTokenHandler.RetrieveRefreshTokenAsync() before it tries to retrieve a new access token, and it will invoke the IRefreshTokenHandler.SaveRefreshTokenAsync() when it receives a new refresh token from the authorization server.

Top

Signing a user out

This section describes how to sign out a user.

Using the REST API to sign a user out

To sign a user out, make a call to the Live Connect authorization web service at the following URL.

Within the larger URL, CLIENT_ID is the corresponding client ID, and REDIRECT_URL is the URL to redirect to after the Live Connect authorization web service successfully signs the user out. The domain portion of this redirect URL must match the one that is specified in the Live Connect app management site for the corresponding client ID.

In this URL example,

  • Replace CLIENT_ID with your app's client ID.
  • Replace REDIRECT_URI with the URI to redirect to after the Live Connect authorization web service successfully signs the user out. The domain portion of this redirect URL must match the one that is specified in the Live Connect app management site for your app's client ID.
https://login.live.com/oauth20_logout.srf?client_id=CLIENT_ID&redirect_uri=REDIRECT_URL

Using the Live Connect SDK for ASP.NET to sign a user out

This example shows how to sign a user out if you are using the Live Connect SDK for ASP.NET.


LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, null);
string loginUrl = liveAuthClient.GetLogoutUrl("http://www.contoso.com/logout");

// Clears the session in the cookie.
liveAuthClient.ClearSession(this.HttpContext); 


Top

ASP.NET and PHP code samples

For examples of calling these code patterns by using ASP.NET and PHP, see the ASP.NET and PHP code samples in the GitHub - LiveSDK collection.

Top

 

 

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.