In the previous article, we have seen how we can integrate our application with dropbox .net SDK and generate a token from UI. you can read that article from here.
So here we will generate an access token using ASP.NET MVC with the help of Dropbox .NET SDK. From the previous article, you already got “App key” and “App Secret”.
To generate access token you need to create redirect URI which returns code and state as a query string. using the below code you can generate redirect URI.
private string RedirectUri { get { if (Request.Url.Host.ToLowerInvariant() == "localhost") { return string.Format("http://{0}:{1}/Home/Auth", this.Request.Url.Host, this.Request.Url.Port); } var builder = new UriBuilder( Uri.UriSchemeHttps, Request.Url.Host) { Path = "/Home/Auth" }; return builder.ToString(); } }
If you are in the local development server “Home” will be replaced with your controller name and “Auth” will be replaced by action name.
Now you need to redirect the user with your app key and get permission from the user to get token for account. Here I’m writing code on /Home/Index page.
public ActionResult Index() { var state = Guid.NewGuid().ToString("N"); var redirect = DropboxOAuth2Helper.GetAuthorizeUri( OAuthResponseType.Code, "appKey", RedirectUri, state); return Redirect(redirect.ToString()); }
This above code will redirect us to the dropbox site to allow application and return code and state in URL.
Here the user will create continue and allow to access his/her account.
When a user clicks on allow, Dropbox redirects to our URL with two extra parameters “code” and “state”. we need to catch this parameter to generate an access token.
By using the below code we can generate an access token and redirect somewhere.
public async Task<ActionResult> Auth(string code, string state) { try { var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync( code, "appKey", "appSecret", this.RedirectUri); var dropboxAccessToken = response.AccessToken; Session["Token"] = dropboxAccessToken; } catch (Exception e) { } return RedirectToAction("IndexSuccess");
OutPut
hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.