protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.pendingRequest = OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequest(); if (this.pendingRequest == null) { throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request."); } this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie(); var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier); this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name); this.scopeLabel.Text = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope)); // Consider auto-approving if safe to do so. if (((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices).CanBeAutoApproved(this.pendingRequest)) { OAuthServiceProvider.AuthorizationServer.ApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name); } this.ViewState["AuthRequest"] = this.pendingRequest; } else { Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value); this.pendingRequest = (EndUserAuthorizationRequest)this.ViewState["AuthRequest"]; } }
/// <summary> /// Approves an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client. /// </summary> /// <param name="authorizationRequest">The authorization request to approve.</param> /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param> /// <param name="nonce">The nonce data.</param> /// <param name="successAccessTokenResponse">The end user authorization success access token response.</param> /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param> /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, string nonce, out EndUserAuthorizationSuccessAccessTokenResponse successAccessTokenResponse, IEnumerable <string> scopes = null, Uri callback = null) { var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, userName, nonce, out successAccessTokenResponse, scopes, callback); this.Channel.Respond(response); }
public ActionResult Authorize() { EndUserAuthorizationRequest pendingRequest = this.m_AuthorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken); if (pendingRequest == null) { throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request"); } var clientInfo = m_ClientRep.Get(s => s.ClientIdentifier == pendingRequest.ClientIdentifier); if (((OAuth2AuthorizationServer)this.m_AuthorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest)) { var approval = this.m_AuthorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name); var response = this.m_AuthorizationServer.Channel.PrepareResponseAsync(approval, Response.ClientDisconnectedToken); Response.ContentType = response.Content.Headers.ContentType.ToString(); return(response.AsActionResult()); } var model = new AccountAuthorizeModel { ClientApp = clientInfo.Name, Scope = pendingRequest.Scope, AuthorizationRequest = pendingRequest }; return(View(model)); }
public bool CanBeAutoApproved(EndUserAuthorizationRequest authorizationRequest) { if (authorizationRequest == null) { throw new ArgumentNullException("authorizationRequest"); } // NEVER issue an auto-approval to a client that would end up getting an access token immediately // (without a client secret), as that would allow arbitrary clients to masquarade as an approved client // and obtain unauthorized access to user data. if (authorizationRequest.ResponseType == EndUserAuthorizationResponseType.AuthorizationCode) { // Never issue auto-approval if the client secret is blank, since that too makes it easy to spoof // a client's identity and obtain unauthorized access. var requestingClient = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == authorizationRequest.ClientIdentifier); if (!string.IsNullOrEmpty(requestingClient.ClientSecret)) { return(this.IsAuthorizationValid( authorizationRequest.Scope, authorizationRequest.ClientIdentifier, DateTime.UtcNow, HttpContext.Current.User.Identity.Name)); } } // Default to not auto-approving. return(false); }
public bool CanBeAutoApproved(EndUserAuthorizationRequest authorizationRequest) { if (authorizationRequest == null) { throw new ArgumentNullException("authorizationRequest"); } return(true); }
/// <summary> /// Approves an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client. /// </summary> /// <param name="authorizationRequest">The authorization request to approve.</param> /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param> /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param> /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable <string> scopes = null, Uri callback = null) { Requires.NotNull(authorizationRequest, "authorizationRequest"); var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, userName, scopes, callback); this.Channel.Respond(response); }
/// <summary> /// Rejects an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client. /// </summary> /// <param name="authorizationRequest">The authorization request to disapprove.</param> /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> public void RejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) { Requires.NotNull(authorizationRequest, "authorizationRequest"); var response = this.PrepareRejectAuthorizationRequest(authorizationRequest, callback); this.Channel.Respond(response); }
protected void Page_Load(object sender, EventArgs e) { try { if (!Request.IsSecureConnection) { throw new HttpException((int)HttpStatusCode.Forbidden, Resources.LocalizedText.oAuthErrNotSecure); } if (!IsPostBack) { if ((m_pendingRequest = this.authorizationServer.ReadAuthorizationRequest()) == null) { throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrMissingRequest); } MFBOauth2Client client = (MFBOauth2Client)authorizationServer.AuthorizationServerServices.GetClient(m_pendingRequest.ClientIdentifier); if (Uri.Compare(m_pendingRequest.Callback, new Uri(client.Callback), UriComponents.HostAndPort | UriComponents.PathAndQuery, UriFormat.UriEscaped, StringComparison.CurrentCultureIgnoreCase) != 0) { throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrBadRedirectURL); } HashSet <string> allowedScopes = OAuthUtilities.SplitScopes(client.Scope); if (!m_pendingRequest.Scope.IsSubsetOf(allowedScopes)) { throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrUnauthorizedScopes); } IEnumerable <MFBOAuthScope> requestedScopes = MFBOauthServer.ScopesFromStrings(m_pendingRequest.Scope); // See if there are any scopes that are requested that are not allowed. IEnumerable <string> lstScopes = MFBOauthServer.ScopeDescriptions(requestedScopes); mvScopesRequested.SetActiveView(lstScopes.Count() == 0 ? vwNoScopes : vwRequestedScopes); rptPermissions.DataSource = lstScopes; rptPermissions.DataBind(); ViewState[szVSKeyPendingRequest] = m_pendingRequest; lblClientName.Text = client.ClientName; } else { m_pendingRequest = (EndUserAuthorizationRequest)ViewState[szVSKeyPendingRequest]; } } catch (HttpException ex) { RejectWithError(ex.Message); } catch (MyFlightbook.MyFlightbookException ex) { lblErr.Text = ex.Message; mvAuthorize.SetActiveView(vwErr); } }
public static bool CanBeAutoApproved(EndUserAuthorizationRequest authorizationRequest) { if (authorizationRequest == null) { throw new ArgumentNullException(nameof(authorizationRequest)); } return(false); }
public EndUserAuthorizationFailedResponse PrepareRejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) { if (callback == null) { callback = this.GetCallback(authorizationRequest); } var response = new EndUserAuthorizationFailedResponse(callback, authorizationRequest); return(response); }
/// <summary> /// Prepares a response to inform the Client that the user has rejected the Client's authorization request. /// </summary> /// <param name="authorizationRequest">The authorization request.</param> /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> /// <returns>The authorization response message to send to the Client.</returns> public EndUserAuthorizationFailedResponse PrepareRejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) { Contract.Ensures(Contract.Result <EndUserAuthorizationFailedResponse>() != null); if (callback == null) { callback = this.GetCallback(authorizationRequest); } var response = new EndUserAuthorizationFailedResponse(callback, authorizationRequest); return(response); }
protected Uri GetCallback(EndUserAuthorizationRequest authorizationRequest) { var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier); if (authorizationRequest.Callback != null) { return(authorizationRequest.Callback); } Uri defaultCallback = client.DefaultCallback; ErrorUtilities.VerifyProtocol(defaultCallback != null, AuthServerStrings.NoCallback); return(defaultCallback); }
protected void Page_Load(object sender, EventArgs e) { this.RegisterAsyncTask( new PageAsyncTask( async ct => { if (!IsPostBack) { this.pendingRequest = await OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequestAsync( new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); if (this.pendingRequest == null) { throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request."); } this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie(); var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier); this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name); this.scopeLabel.Text = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope)); // Consider auto-approving if safe to do so. if ( ((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices) .CanBeAutoApproved(this.pendingRequest)) { var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest( this.pendingRequest, HttpContext.Current.User.Identity.Name); var responseMessage = await OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync( response, Response.ClientDisconnectedToken); await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); this.Context.Response.End(); } this.ViewState["AuthRequest"] = this.pendingRequest; } else { Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value); this.pendingRequest = (EndUserAuthorizationRequest)this.ViewState["AuthRequest"]; } })); }
/// <summary> /// Gets the redirect URL to use for a particular authorization request. /// </summary> /// <param name="authorizationRequest">The authorization request.</param> /// <returns>The URL to redirect to. Never <c>null</c>.</returns> /// <exception cref="ProtocolException">Thrown if no callback URL could be determined.</exception> protected Uri GetCallback(EndUserAuthorizationRequest authorizationRequest) { Contract.Ensures(Contract.Result <Uri>() != null); var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier); // Prefer a request-specific callback to the pre-registered one (if any). if (authorizationRequest.Callback != null) { // The OAuth channel has already validated the callback parameter against // the authorization server's whitelist for this client. return(authorizationRequest.Callback); } // Since the request didn't include a callback URL, look up the callback from // the client's preregistration with this authorization server. Uri defaultCallback = client.DefaultCallback; ErrorUtilities.VerifyProtocol(defaultCallback != null, AuthServerStrings.NoCallback); return(defaultCallback); }
public ActionResult Authorize() { // Have DotNetOpenAuth read the info we need out of the request EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest(); if (pendingRequest == null) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Missing authorization request."); } // Make sure the client is one we recognize Client requestingClient = _clientRepository.GetById(pendingRequest.ClientIdentifier); if (requestingClient == null) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request"); } // Ensure client is allowed to use the requested scopes if (!pendingRequest.Scope.IsSubsetOf(requestingClient.SupportedScopes)) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request"); } // Consider auto-approving if safe, so user doesn't have to authorize repeatedly. // Leaving this step out for now // Show user the authorization page by which they can authorize this client to access their // data within the resource determined by the requested scopes var model = new AccountAuthorizeModel { Client = requestingClient, Scopes = requestingClient.Scopes.Where(x => pendingRequest.Scope.Contains(x.Identifier)).ToList(), AuthorizationRequest = pendingRequest }; return(View(model)); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { // Figure out what resource the request is intending to access to see if the // user has already authenticated to with it EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest(); if (pendingRequest == null) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Missing authorization request."); } try { _targetResource = _resourceRepository.FindWithSupportedScopes(pendingRequest.Scope); // Above will return null if no resource supports all of the requested scopes if (_targetResource == null) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Bad authorization request."); } } catch (Exception) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Bad authorization request."); } // User is considered authorized if in possession of token that originated from the resource's login page, // Name of token is determined by the resource configuration string tokenName = _targetResource.AuthenticationTokenName; string encryptedToken = httpContext.Request[tokenName]; //could be in cookie if previously logged in, or querystring if just logged in if (string.IsNullOrWhiteSpace(encryptedToken)) { // No token, so unauthorized return(false); } // Validate this thing came from us via shared secret with the resource's login page // The implementation here ideally could be generalized a bit better or standardized string encryptionKey = _targetResource.AuthenticationKey; string decryptedToken = EncodingUtility.Decode(encryptedToken, encryptionKey); string[] tokenContentParts = decryptedToken.Split(';'); string name = tokenContentParts[0]; DateTime loginDate = DateTime.Parse(tokenContentParts[1]); bool storeCookie = bool.Parse(tokenContentParts[2]); if ((DateTime.Now.Subtract(loginDate) > TimeSpan.FromDays(7))) { // Expired, remove cookie if present and flag user as unauthorized httpContext.Response.Cookies.Remove(tokenName); return(false); } // Things look good. // Set principal for the authorization server IIdentity identity = new GenericIdentity(name); httpContext.User = new GenericPrincipal(identity, null); // If desired, persist cookie so user doesn't have to authenticate with the resource over and over var cookie = new HttpCookie(tokenName, encryptedToken); if (storeCookie) { cookie.Expires = DateTime.Now.AddDays(7); // could parameterize lifetime } httpContext.Response.AppendCookie(cookie); return(true); }
/// <summary> /// Approves an authorization request. /// </summary> /// <param name="authorizationRequest">The authorization request to approve.</param> /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param> /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param> /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> /// <returns>The authorization response message to send to the Client.</returns> public EndUserAuthorizationSuccessResponseBase PrepareApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable <string> scopes = null, Uri callback = null) { Requires.NotNull(authorizationRequest, "authorizationRequest"); Requires.NotNullOrEmpty(userName, "userName"); Contract.Ensures(Contract.Result <EndUserAuthorizationSuccessResponseBase>() != null); if (callback == null) { callback = this.GetCallback(authorizationRequest); } var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier); EndUserAuthorizationSuccessResponseBase response; switch (authorizationRequest.ResponseType) { case EndUserAuthorizationResponseType.AccessToken: IAccessTokenRequestInternal accessRequestInternal = (EndUserAuthorizationImplicitRequest)authorizationRequest; var accessTokenResult = this.AuthorizationServerServices.CreateAccessToken(accessRequestInternal); ErrorUtilities.VerifyHost(accessTokenResult != null, "IAuthorizationServerHost.CreateAccessToken must not return null."); accessRequestInternal.AccessTokenResult = accessTokenResult; var implicitGrantResponse = new EndUserAuthorizationSuccessAccessTokenResponse(callback, authorizationRequest); implicitGrantResponse.Lifetime = accessTokenResult.AccessToken.Lifetime; accessTokenResult.AccessToken.ApplyAuthorization(implicitGrantResponse.Scope, userName, implicitGrantResponse.Lifetime); IAccessTokenCarryingRequest tokenCarryingResponse = implicitGrantResponse; tokenCarryingResponse.AuthorizationDescription = accessTokenResult.AccessToken; response = implicitGrantResponse; break; case EndUserAuthorizationResponseType.AuthorizationCode: var authCodeResponse = new EndUserAuthorizationSuccessAuthCodeResponseAS(callback, authorizationRequest); IAuthorizationCodeCarryingRequest codeCarryingResponse = authCodeResponse; codeCarryingResponse.AuthorizationDescription = new AuthorizationCode( authorizationRequest.ClientIdentifier, authorizationRequest.Callback, authCodeResponse.Scope, userName); response = authCodeResponse; break; default: throw ErrorUtilities.ThrowInternal("Unexpected response type."); } response.AuthorizingUsername = userName; // Customize the approved scope if the authorization server has decided to do so. if (scopes != null) { response.Scope.ResetContents(scopes); } return(response); }
public ActionResult ProcessAuthorization(bool isApproved) { // Have DotNetOpenAuth read the info we need out of the request EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest(); if (pendingRequest == null) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Missing authorization request."); } // Make sure the client is one we recognize Client requestingClient = _clientRepository.GetById(pendingRequest.ClientIdentifier); if (requestingClient == null) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request"); } // Make sure the resource is defined, it definitely should be due to the ResourceAuthenticated attribute Resource requestedResource = _resourceRepository.FindWithSupportedScopes(pendingRequest.Scope); if (requestedResource == null) { throw new HttpException(Convert.ToInt32(HttpStatusCode.BadRequest), "Invalid request"); } // See if authorization of this client was approved by the user // At this point, the user either agrees to the entire scope requested by the client or none of it. // If we gave capability for user to reduce scope to give client less access, some changes would be required here IDirectedProtocolMessage authRequest; if (isApproved) { // Add user to our repository if this is their first time var requestingUser = _userRepository.GetById(User.Identity.Name); if (requestingUser == null) { requestingUser = new User { Id = User.Identity.Name, CreateDateUtc = DateTime.UtcNow }; _userRepository.Insert(requestingUser); _userRepository.Save(); } // The authorization we file in our database lasts until the user explicitly revokes it. // You can cause the authorization to expire by setting the ExpirationDateUTC // property in the below created ClientAuthorization. _authorizationRepository.Insert(new Authorization { ClientId = requestingClient.Id, Scope = OAuthUtilities.JoinScopes(pendingRequest.Scope), UserId = requestingUser.Id, ResourceId = requestedResource.Id, CreatedOnUtc = DateTime.UtcNow }); _authorizationRepository.Save(); // Have DotNetOpenAuth generate an approval to send back to the client authRequest = _authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name); } else { // Have DotNetOpenAuth generate a rejection to send back to the client authRequest = _authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest); // The PrepareResponse call below is giving an error of "The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationFailedResponse message: error" // unless I do this..... var msg = (EndUserAuthorizationFailedResponse)authRequest; msg.Error = "User denied your request"; } // This will redirect to the client app using their defined callback, so they can handle // the approval or rejection as they see fit return(_authorizationServer.Channel.PrepareResponse(authRequest).AsActionResult()); }
/// <summary> /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAuthCodeResponseAS"/> class. /// </summary> /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> /// <param name="request">The authorization request from the user agent on behalf of the client.</param> internal EndUserAuthorizationSuccessAuthCodeResponseAS(Uri clientCallback, EndUserAuthorizationRequest request) : base(clientCallback, request) { ((IMessageWithClientState)this).ClientState = request.ClientState; }
protected void Page_Load(object sender, EventArgs e) { try { if (!Request.IsSecureConnection) { throw new HttpException((int)HttpStatusCode.Forbidden, Resources.LocalizedText.oAuthErrNotSecure); } if (!IsPostBack) { if ((m_pendingRequest = this.authorizationServer.ReadAuthorizationRequest()) == null) { throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrMissingRequest); } MFBOauth2Client client = (MFBOauth2Client)authorizationServer.AuthorizationServerServices.GetClient(m_pendingRequest.ClientIdentifier); bool fIsValidCallback = false; foreach (string callback in client.Callbacks) { if (Uri.Compare(m_pendingRequest.Callback, new Uri(callback), UriComponents.HostAndPort | UriComponents.PathAndQuery, UriFormat.SafeUnescaped, StringComparison.CurrentCultureIgnoreCase) == 0) { fIsValidCallback = true; break; } } if (!fIsValidCallback) { throw new HttpException((int)HttpStatusCode.BadRequest, String.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.LocalizedText.oAuthErrBadRedirectURL, m_pendingRequest.Callback.ToString())); } HashSet <string> allowedScopes = OAuthUtilities.SplitScopes(client.Scope); if (!m_pendingRequest.Scope.IsSubsetOf(allowedScopes)) { throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrUnauthorizedScopes); } IEnumerable <MFBOAuthScope> requestedScopes = MFBOauthServer.ScopesFromStrings(m_pendingRequest.Scope); // See if there are any scopes that are requested that are not allowed. IEnumerable <string> lstScopes = MFBOauthServer.ScopeDescriptions(requestedScopes); mvScopesRequested.SetActiveView(!lstScopes.Any() ? vwNoScopes : vwRequestedScopes); rptPermissions.DataSource = lstScopes; rptPermissions.DataBind(); ViewState[szVSKeyPendingRequest] = m_pendingRequest; lblClientName.Text = HttpUtility.HtmlEncode(client.ClientName); } else { m_pendingRequest = (EndUserAuthorizationRequest)ViewState[szVSKeyPendingRequest]; } } catch (Exception ex) when(ex is HttpException || ex is ProtocolException || ex is ProtocolFaultResponseException || ex is MyFlightbook.MyFlightbookException) { lblErr.Text = ex.Message; mvAuthorize.SetActiveView(vwErr); } }
public bool CanBeAutoApproved(EndUserAuthorizationRequest authorizationRequest) { //For the sake of this exercise, don't auto-approve anyone. return(false); }
/// <summary> /// Create a authorise token from the request. Returns the bdy html result. /// </summary> /// <param name="httpRequest">The current http request.</param> /// <param name="rawUri">A System.Uri object containing information regarding the URL of the current request.</param> /// <param name="queryString">The collection of HTTP query string variables.</param> /// <param name="form">The collection of form variables.</param> /// <param name="headers">The collection of HTTP headers.</param> /// <param name="cookies">The collection of cookies sent by the client.</param> /// <param name="returnType">The type of response to return.</param> /// <param name="responseHeaders">The response headers for the request.</param> /// <param name="isApprovedByUser">Has the user approved the client to access the resources.</param> /// <returns>The formatted redirect url; else null.</returns> private object CreateAuthorise(HttpRequestBase httpRequest, Uri rawUri, NameValueCollection queryString, NameValueCollection form, NameValueCollection headers, HttpCookieCollection cookies, int returnType, out System.Net.WebHeaderCollection responseHeaders, bool isApprovedByUser) { IDirectedProtocolMessage response = null; OutgoingWebResponse webResponse = null; string clientID = null; string nonce = null; string codeKey = null; try { // Make sure that all the passed parameters are valid. if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } if (rawUri == null) { throw new ArgumentNullException("rawUri"); } if (queryString == null) { throw new ArgumentNullException("queryString"); } if (form == null) { throw new ArgumentNullException("form"); } if (headers == null) { throw new ArgumentNullException("headers"); } if (cookies == null) { throw new ArgumentNullException("cookies"); } // Read the request make sure it is valid. EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest(httpRequest); if (pendingRequest == null) { throw new Exception("Missing authorization request."); } // Only process if the user has approved the request. if (isApprovedByUser) { // Make sure all maditor parameters are present. _oAuthAuthorizationServer.ValidateAuthoriseRequestParametersAbsent(queryString); if (_oAuthAuthorizationServer.ParametersAbsent.Count() > 0) { throw new Exception("Some authorisation request parameters are missing."); } // Assign each query string parameter. clientID = pendingRequest.ClientIdentifier; string callback = pendingRequest.Callback.ToString(); string state = pendingRequest.ClientState; string scope = OAuthUtilities.JoinScopes(pendingRequest.Scope); string responseType = (pendingRequest.ResponseType == EndUserAuthorizationResponseType.AccessToken ? "token" : "code"); string companyUniqueUserID = queryString["com_unique_uid"]; // Set the crytography key store values. _authorizationServer.AuthorizationServerServices.CryptoKeyStore.ExpiryDateTime = DateTime.UtcNow.AddYears(1); _authorizationServer.AuthorizationServerServices.CryptoKeyStore.ClientIndetifier = clientID; _authorizationServer.AuthorizationServerServices.CryptoKeyStore.GetCodeKey = false; // Create a new nonce and store it in the nonce store. nonce = _nonceStore.GenerateNonce(); _nonceStore.StoreNonce(DateTime.UtcNow, nonce, clientID); // Create the access token from the stores, and create a new verification code. string verifier = _consumerStore.SetVerificationCode(clientID, nonce, companyUniqueUserID, scope); EndUserAuthorizationSuccessAccessTokenResponse successAccessTokenResponse = null; // Prepare the request. pass the nonce and join the userID and nonce of // the user that approved the resource access request. response = _authorizationServer.PrepareApproveAuthorizationRequest( pendingRequest, companyUniqueUserID + "_" + nonce, nonce, out successAccessTokenResponse); // Prepare the authorisation response. webResponse = _authorizationServer.Channel.PrepareResponse(response); // Create the query collection of the code request // and extract the code value that is to be sent // the the client. NameValueCollection queryResponseString = new NameValueCollection(); Uri uriRequest = webResponse.GetDirectUriRequest(_authorizationServer.Channel); // For each query item. string[] queries = uriRequest.Query.Split(new char[] { '&' }); foreach (string query in queries) { // Add the query name and value to the collection. string[] queriesNameValue = query.Split(new char[] { '=' }); queryResponseString.Add(queriesNameValue[0].TrimStart(new char[] { '?' }), queriesNameValue[1]); } // What type of response is to be handled. switch (pendingRequest.ResponseType) { case EndUserAuthorizationResponseType.AuthorizationCode: // The user has requested a code, this is // used so the client can get a token later. // If the code response type exits. if (queryResponseString["code"] != null) { codeKey = HttpUtility.UrlDecode(queryResponseString["code"]); } // Insert the code key (code or token); if (!String.IsNullOrEmpty(codeKey)) { _tokenStore.StoreCodeKey(clientID, nonce, codeKey); } break; case EndUserAuthorizationResponseType.AccessToken: // This is used so the client is approved and a token is sent back. // Update the access token. if (successAccessTokenResponse != null) { if (!String.IsNullOrEmpty(successAccessTokenResponse.AccessToken)) { _tokenStore.UpdateAccessToken(successAccessTokenResponse.AccessToken, nonce); } } break; } } else { // Send an error response. response = _authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest); } // What type should be returned. switch (returnType) { case 0: // A URI request redirect only. responseHeaders = webResponse.Headers; return(webResponse.GetDirectUriRequest(_authorizationServer.Channel)); case 1: // The complete html body. responseHeaders = webResponse.Headers; return(webResponse.Body); default: // Default is the complete html body. responseHeaders = webResponse.Headers; return(webResponse.Body); } } catch (Exception ex) { // Get the current token errors. responseHeaders = null; _tokenError = ex.Message; return(null); } }