Class DropboxOAuth2Helper
Contains methods that make authorizing with Dropbox easier.
Inheritance
Inherited Members
Namespace: Dropbox.Api
Assembly: Dropbox.Api.dll
Syntax
public static class DropboxOAuth2Helper
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, TokenAccessType, String[], IncludeGrantedScopes, String) to create the URI with response type
set to Token for token flow.
System.Guid.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 System.Net.HttpListener is created to listen to the RedirectUri
which will later receive redirect callback from
the server. System.Diagnostics.Process.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.Token, 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, TokenAccessType, String[], IncludeGrantedScopes, String) 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.
System.Guid.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, String). 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");
}
Methods
| Improve this Doc View SourceGeneratePKCECodeChallenge(String)
Hashes a PKCE code verifier to generate a code challenge.
Declaration
public static string GeneratePKCECodeChallenge(string codeVerifier)
Parameters
Type | Name | Description |
---|---|---|
System.String | codeVerifier | The PKCE code verifier. |
Returns
Type | Description |
---|---|
System.String | The PKCE code challenge. |
GeneratePKCECodeVerifier()
Generates a PKCE code verifier.
Declaration
public static string GeneratePKCECodeVerifier()
Returns
Type | Description |
---|---|
System.String | The PKCE code verifier. |
GetAuthorizeUri(OAuthResponseType, String, String, String, Boolean, Boolean, String, Boolean, TokenAccessType, String[], IncludeGrantedScopes, String)
Gets the URI used to start the OAuth2.0 authorization flow.
Declaration
public static Uri GetAuthorizeUri(OAuthResponseType oauthResponseType, string clientId, string redirectUri = null, string state = null, bool forceReapprove = false, bool disableSignup = false, string requireRole = null, bool forceReauthentication = false, TokenAccessType tokenAccessType = TokenAccessType.Legacy, string[] scopeList = null, IncludeGrantedScopes includeGrantedScopes = IncludeGrantedScopes.None, string codeChallenge = null)
Parameters
Type | Name | Description |
---|---|---|
OAuthResponseType | oauthResponseType | The grant type requested, either |
System.String | clientId | The apps key, found in the App Console. |
System.String | redirectUri | Where to redirect the user after authorization has completed. This must be the exact URI
registered in the App Console; even |
System.String | state | Up to 500 bytes of arbitrary data that will be passed back to |
System.Boolean | forceReapprove | Whether or not to force the user to approve the app again if they've already done so.
If |
System.Boolean | disableSignup | When |
System.String | requireRole | If this parameter is specified, the user will be asked to authorize with a particular type of Dropbox account, either work for a team account or personal for a personal account. Your app should still verify the type of Dropbox account after authorization since the user could modify or remove the require_role parameter. |
System.Boolean | forceReauthentication | If |
TokenAccessType | tokenAccessType | Determines the type of token to request. See TokenAccessType for information on specific types available. If none is specified, this will use the legacy type. |
System.String[] | scopeList | list of scopes to request in base oauth flow. If left blank, will default to all scopes for app. |
IncludeGrantedScopes | includeGrantedScopes | which scopes to include from previous grants. Note: if this user has never linked the app, include_granted_scopes must be None. |
System.String | codeChallenge | If using PKCE, please us the PKCEOAuthFlow object. |
Returns
Type | Description |
---|---|
System.Uri | The uri of a web page which must be displayed to the user in order to authorize the app. |
GetAuthorizeUri(OAuthResponseType, String, Uri, String, Boolean, Boolean, String, Boolean, TokenAccessType, String[], IncludeGrantedScopes, String)
Gets the URI used to start the OAuth2.0 authorization flow.
Declaration
public static Uri GetAuthorizeUri(OAuthResponseType oauthResponseType, string clientId, Uri redirectUri = null, string state = null, bool forceReapprove = false, bool disableSignup = false, string requireRole = null, bool forceReauthentication = false, TokenAccessType tokenAccessType = TokenAccessType.Legacy, string[] scopeList = null, IncludeGrantedScopes includeGrantedScopes = IncludeGrantedScopes.None, string codeChallenge = null)
Parameters
Type | Name | Description |
---|---|---|
OAuthResponseType | oauthResponseType | The grant type requested, either |
System.String | clientId | The apps key, found in the App Console. |
System.Uri | redirectUri | Where to redirect the user after authorization has completed. This must be the exact URI
registered in the App Console; even |
System.String | state | Up to 500 bytes of arbitrary data that will be passed back to |
System.Boolean | forceReapprove | Whether or not to force the user to approve the app again if they've already done so.
If |
System.Boolean | disableSignup | When |
System.String | requireRole | If this parameter is specified, the user will be asked to authorize with a particular type of Dropbox account, either work for a team account or personal for a personal account. Your app should still verify the type of Dropbox account after authorization since the user could modify or remove the require_role parameter. |
System.Boolean | forceReauthentication | If |
TokenAccessType | tokenAccessType | Determines the type of token to request. See TokenAccessType for information on specific types available. If none is specified, this will use the legacy type. |
System.String[] | scopeList | list of scopes to request in base oauth flow. If left blank, will default to all scopes for app. |
IncludeGrantedScopes | includeGrantedScopes | which scopes to include from previous grants. Note: if this user has never linked the app, include_granted_scopes must be None. |
System.String | codeChallenge | If using PKCE, please us the PKCEOAuthFlow object. |
Returns
Type | Description |
---|---|
System.Uri | The uri of a web page which must be displayed to the user in order to authorize the app. |
GetAuthorizeUri(String, Boolean)
Gets the URI used to start the OAuth2.0 authorization flow which doesn't require a redirect URL.
Declaration
public static Uri GetAuthorizeUri(string clientId, bool disableSignup = false)
Parameters
Type | Name | Description |
---|---|---|
System.String | clientId | The apps key, found in the App Console. |
System.Boolean | disableSignup | When |
Returns
Type | Description |
---|---|
System.Uri | The uri of a web page which must be displayed to the user in order to authorize the app. |
ParseTokenFragment(Uri)
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.
Declaration
public static OAuth2Response ParseTokenFragment(Uri redirectedUri)
Parameters
Type | Name | Description |
---|---|---|
System.Uri | redirectedUri | The redirected URI. |
Returns
Type | Description |
---|---|
OAuth2Response | The authorization response, containing the access token and uid of the authorized user. |
ProcessCodeFlowAsync(String, String, String, String, HttpClient, String)
Processes the second half of the OAuth 2.0 code flow.
Declaration
public static async Task<OAuth2Response> ProcessCodeFlowAsync(string code, string appKey, string appSecret = null, string redirectUri = null, HttpClient client = null, string codeVerifier = null)
Parameters
Type | Name | Description |
---|---|---|
System.String | code | The code acquired in the query parameters of the redirect from the initial authorize url. |
System.String | appKey | The application key, found in the App Console. |
System.String | appSecret | The application secret, found in the App Console This is optional if using PKCE. |
System.String | redirectUri | The redirect URI that was provided in the initial authorize URI, this is only used to validate that it matches the original request, it is not used to redirect again. |
HttpClient | client | An optional http client instance used to make requests. |
System.String | codeVerifier | The code verifier for PKCE flow. If using PKCE, please us the PKCEOauthFlow object. |
Returns
Type | Description |
---|---|
System.Threading.Tasks.Task<OAuth2Response> | The authorization response, containing the access token and uid of the authorized user. |
ProcessCodeFlowAsync(Uri, String, String, String, String, HttpClient, String)
Processes the second half of the OAuth 2.0 code flow.
Declaration
public static Task<OAuth2Response> ProcessCodeFlowAsync(Uri responseUri, string appKey, string appSecret, string redirectUri = null, string state = null, HttpClient client = null, string codeVerifier = null)
Parameters
Type | Name | Description |
---|---|---|
System.Uri | responseUri | The URI to which the user was redirected after the initial authorization request. |
System.String | appKey | The application key, found in the App Console. |
System.String | appSecret | The application secret, found in the App Console. |
System.String | redirectUri | The redirect URI that was provided in the initial authorize URI, this is only used to validate that it matches the original request, it is not used to redirect again. |
System.String | state | The state parameter (if any) that matches that used in the initial authorize URI. |
HttpClient | client | An optional http client instance used to make requests. |
System.String | codeVerifier | The code verifier for PKCE flow. If using PKCE, please us the PKCEOauthFlow object. |
Returns
Type | Description |
---|---|
System.Threading.Tasks.Task<OAuth2Response> | The authorization response, containing the access token and uid of the authorized user. |