/// <summary> /// The first step of the OAuth2 flow. Redirect the user to Box for credentialing and authorization of this application. /// </summary> // GET /Authorize public ActionResult Authorize(AuthModel authModel) { // Generate and stash an antiforgery token var antiforgeryToken = Guid.NewGuid().ToString(); Session[AntiforgeryToken] = antiforgeryToken; // Stash the Client ID/Secret for easy access when the user is redirected back to this page. Session[ClientId] = authModel.ClientId; Session[ClientSecret] = authModel.ClientSecret; // Redirect the user to Box's OAuth2 authorization page string authUrl = string.Format("https://app.box.com/api/oauth2/authorize?response_type=code&client_id={0}&state={1}", authModel.ClientId, antiforgeryToken); return new RedirectResult(authUrl); }
/// <summary> /// The second and final step of the OAuth2 flow. The user has authorized this application at Box's site and redirected them back to this site. Validate the redirect and exchange the authorization code for a access/refresh token pair. /// </summary> private async Task<ActionResult> Token(string code, string state) { try { // Validate that the 'code' has not already been exchanged for an access token. This prevents replay attacks. if (!ValidateAntiforgeryToken(state)) { Response.StatusCode = 400; return View("Error", new ErrorModel { Message = "forged_request", Description = "This code has already been used to fetch an authorization token." }); } // Fetch the stashed Client ID/Secret from the Session var clientId = ClientId ;// Session[ClientId] as string; var clientSecret = ClientSecret;// Session[ClientSecret] as string; // Exchange the 'code' for an authorization/refresh token pair // var authSession = await ExchangeCodeForTokenPair(code, clientId, clientSecret); var boxClient = new BoxClient(new BoxConfig(clientId, clientSecret, new Uri("http://localhost:1176/Auth/Callback"))); OAuthSession authSession = await boxClient.Auth.AuthenticateAsync(code); // TODO: // Clear out the session variables for security ClearSession(); var authInfo = new AuthModel { ClientId = clientId, ClientSecret = clientSecret, AuthToken = authSession.AccessToken, RefreshToken = authSession.RefreshToken }; return View("Index", authInfo); } catch (BoxException e) { // Response.StatusCode = (int)e.StatusCode; return Error(". . .", e.Message); } catch (Exception e) { Response.StatusCode = 500; return Error(e.Message, e.StackTrace); } }