Click or drag to resize

DropboxOAuth2Helper Class

Contains methods that make authorizing with Dropbox easier.
Inheritance Hierarchy
SystemObject
  Dropbox.ApiDropboxOAuth2Helper

Namespace:  Dropbox.Api
Assembly:  Dropbox.Api (in Dropbox.Api.dll) Version: 4.0
Syntax
public static class DropboxOAuth2Helper

The DropboxOAuth2Helper type exposes the following members.

Methods
  NameDescription
Public methodStatic memberGetAuthorizeUri(String, Boolean)
Gets the URI used to start the OAuth2.0 authorization flow which doesn't require a redirect URL.
Public methodStatic memberGetAuthorizeUri(OAuthResponseType, String, String, String, Boolean, Boolean, String, Boolean)
Public methodStatic memberGetAuthorizeUri(OAuthResponseType, String, Uri, String, Boolean, Boolean, String, Boolean)
Public methodStatic memberParseTokenFragment
Parses the token fragment. When using the OAuth 2.0 token or implicit grant flow, the user will be redirected to a URI with a fragment containing the authorization token.
Public methodStatic memberProcessCodeFlowAsync(String, String, String, String, HttpClient)
Processes the second half of the OAuth 2.0 code flow.
Public methodStatic memberProcessCodeFlowAsync(Uri, String, String, String, String, HttpClient)
Processes the second half of the OAuth 2.0 code flow.
Top
Examples

This shows an example of how to use the token flow. This is part of a Windows Console or WPF app.

The GetAccessToken() method calls GetAuthorizeUri(OAuthResponseType, String, String, String, Boolean, Boolean, String, Boolean) to create the URI with response type set to Token for token flow.

NewGuid is called to generate a random string to use as the state argument, this value can also be used to store application context and prevent cross-site request forgery.

A HttpListener is created to listen to the RedirectUri which will later receive redirect callback from the server. Start is called to launch a native browser and navigate user to the authorize URI. The RedirectUri needs to be registered at App Console. It's common to use value like http://127.0.0.1:{some_avaialble_port}.

After user successfully authorizes the request, HandleOAuth2Redirect receives the redirect callback which contains state and access token as URL fragment. Since the server cannot receive URL fragment directly, it calls RespondPageWithJSRedirect to respond with a HTML page which runs JS code and sends URL fragment as query string parameter to a separate JSRedirect endpoint.

HandleJSRedirect is called to handle redirect from JS code and processes OAuth response from query string. This returns an OAuth2Response containing the access token that will be passed to the DropboxClient constructor.

private async Task HandleOAuth2Redirect(HttpListener http)
{
    var context = await http.GetContextAsync();

    // We only care about request to RedirectUri endpoint.
    while (context.Request.Url.AbsolutePath != RedirectUri.AbsolutePath)
    {
        context = await http.GetContextAsync();
    }

    // Respond with a HTML page which runs JS to send URl fragment.
    RespondPageWithJSRedirect();
}


private async Task<OAuth2Response> HandleJSRedirect(HttpListener http)
{
    var context = await http.GetContextAsync();

    // We only care about request to TokenRedirectUri endpoint.
    while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath)
    {
        context = await http.GetContextAsync();
    }

    var redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]);

    var result = DropboxOAuth2Helper.ParseTokenFragment(redirectUri);

    return result;
}

private async Task GetAccessToken() {
    var state = Guid.NewGuid().ToString("N");
    var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, ApiKey, new Uri(RedirectUri), state: state);

    var http = new HttpListener();
    http.Prefixes.Add(RedirectUri);
    http.Start();

    System.Diagnostics.Process.Start(authorizeUri.ToString());

    // Handle OAuth redirect and send URL fragment to local server using JS.
    await HandleOAuth2Redirect(http);

    // Handle redirect from JS and process OAuth response.
    var result = await HandleJSRedirect(http);

    if (result.State != state)
    {
        // The state in the response doesn't match the state in the request.
        return null;
    }

    Settings.Default.AccessToken = result.AccessToken;
}

This shows an example of how to use the code flow. This is part of a controller class on an ASP.Net MVC website.

The Connect() method calls GetAuthorizeUri(OAuthResponseType, String, String, String, Boolean, Boolean, String, Boolean) to create the URI that the browser component navigate to; the response type is set to Code to create a URI for the code flow.

NewGuid is called to generate a random string to use as the state argument, this value is stored on a field in the web app's user database associated with the current user, this helps prevent cross-site request forgery.

The AuthAsync method handles the route represented by the RedirectUri. The ASP.Net infrastructure has already parsed the query string and extracted the code and state arguments. After validating that the state matches the value stored in the user record in the Connect method, authorization is completed by calling ProcessCodeFlowAsync(String, String, String, String, HttpClient). This returns an OAuth2Response containing the access token that will be passed to the DropboxClient constructor.

// GET: /Home/Connect
public ActionResult Connect()
{
    var user = this.store.CurrentUser();
    user.ConnectState = Guid.NewGuid().ToString("N");
    this.store.SaveChanges();

    var redirect = DropboxOAuth2Helper.GetAuthorizeUri(OauthResponseType.Code, AppKey, RedirectUri, user.ConnectState);
    return Redirect(redirect.ToString());
}

// GET: /Home/Auth
public async Task<ActionResult> AuthAsync(string code, string state)
{
    var user = this.store.CurrentUser();

    if (user.ConnectState != state)
    {
        this.Flash("There was an error connecting to Dropbox.");
        return this.RedirectToAction("Index");
    }

    OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, AppKey, AppSecret, RedirectUri);

    user.DropboxAccessToken = response.AccessToken;
    await this.store.SaveChangesAsync();

    this.Flash("This account has been connected to Dropbox.");
    return this.RedirectToAction("Profile");
}
See Also