Server-side scenarios

This topic shows you how to access OneDrive from your web server.

In this article
In this article
Get an authorization code
Getting tokens
Using an access token to work with a user's info
Using a refresh token to get a new access token and a new refresh token
Signing a user out
ASP.NET and PHP code samples

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 SDK JavaScript API to access services. Some examples of when you might prefer to access services integrated with Microsoft account from your web server include when you want to:

  • Keep track of user sessions that use services integrated with Microsoft account.

  • 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 OneDrive from your web server, you can use the Representational State Transfer (REST) API or the Live SDK for ASP.NET in server-side scripts.

Note

This topic describes how to access OneDrive using the Live SDK for ASP.NET. To access services using REST, see Using the REST API.

In this article

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

  1. Prompt the user to sign in to a service integrated with Microsoft account, and consent to the scopes that you have requested.

  2. If the user successfully signs in and consents, capture the authorization code that the service authorization web service returns to you.

  3. Use the authorization code to call the service 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 SDK 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 SDK 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.

Get 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.

This example shows how you can construct the URL if you are using the Live 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");

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 SDK 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 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.

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.

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.

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();
}

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.

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();
    }
}
  • 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.

Signing a user out

This section describes how to sign out a user.

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); 

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.