/// <summary> /// Send a Bad Request response with the OAuthRequestException details in the header /// and the response parameters in the body. /// </summary> /// <param name="context">HTTP context</param> /// <param name="exception">OAuth exception</param> /// <param name="responseParameters">Response parameters</param> public static void SendBadRequest(HttpContext context, OAuthRequestException exception, NameValueCollection responseParameters) { if (context == null) { throw new ArgumentNullException("context"); } if (exception == null) { throw new ArgumentNullException("exception"); } // There is a problem with the parameters; return 400 Bad Request context.Response.StatusCode = (int)HttpStatusCode.BadRequest; // Add the problem report in the WWW-Authenticate header context.Response.AddHeader( Constants.WwwAuthenticateHeaderParameter, exception.ToHeaderFormat(ServiceProviderContext.Settings.AuthenticationRealm)); // Write the response if (responseParameters != null && responseParameters.Count > 0) { context.Response.Write(Rfc3986.EncodeAndJoin(responseParameters)); } context.Response.End(); }
public static void SetSigningProvider(HttpContext httpContext, OAuthRequestContext context) { /* * Check there is a signing provider for the signature method */ ISigningProvider signingProvider = ServiceProviderContext.GetSigningProvider(context.Parameters.SignatureMethod); if (signingProvider == null) { // There is no signing provider for this signature method OAuthRequestException.ThrowSignatureMethodRejected(null); } // Double check the signing provider declares that it can handle the signature method if (!signingProvider.SignatureMethod.Equals(context.Parameters.SignatureMethod)) { OAuthRequestException.ThrowSignatureMethodRejected(null); } // Ask the signing provider to check the request for pre-conditions if (!signingProvider.CheckRequest(httpContext.Request)) { OAuthRequestException.ThrowSignatureMethodRejected(null); } context.SigningProvider = signingProvider; }
protected virtual void CheckVerifier(HttpContext httpContext, OAuthRequestContext requestContext) { if (!ServiceProviderContext.VerificationProvider.IsValid(requestContext.RequestToken, requestContext.Parameters.Verifier)) { OAuthRequestException.ThrowParametersRejected(new string[] { Constants.VerifierParameter }, "Invalid verifier for request token."); } }
protected virtual void SetRequestToken(HttpContext httpContext, OAuthRequestContext requestContext) { /* * Check the token */ IRequestToken token; if (ServiceProviderContext.TokenStore.ContainsRequestToken(requestContext.Parameters.Token)) { token = ServiceProviderContext.TokenStore.GetRequestToken(requestContext.Parameters.Token); /* * Ensure the token was issued to the same consumer as this request purports * to be from. */ if (!token.ConsumerKey.Equals(requestContext.Parameters.ConsumerKey)) { OAuthRequestException.ThrowTokenRejected(null); } /* * Ensure the token is valid */ if (token == null) { OAuthRequestException.ThrowTokenRejected(null); } else { switch (token.Status) { case TokenStatus.Authorized: requestContext.RequestToken = token; break; case TokenStatus.Expired: OAuthRequestException.ThrowTokenExpired(null); break; case TokenStatus.Used: OAuthRequestException.ThrowTokenUsed(null); break; case TokenStatus.Revoked: OAuthRequestException.ThrowTokenRevoked(null); break; case TokenStatus.Unauthorized: case TokenStatus.Unknown: default: OAuthRequestException.ThrowTokenRejected(null); break; } } } else { OAuthRequestException.ThrowTokenRejected(null); } }
private IActionResult OAuthRequestExceptionToJsonResult(OAuthRequestException oAuthRequestException) { return(new JsonResult(new TokenResponse { Error = oAuthRequestException.Error, ErrorDescription = oAuthRequestException.ErrorDescription, })); }
protected virtual void SetAccessToken(HttpApplication application, OAuthRequestContext context) { IAccessToken accessToken = null; if (context.Parameters.Token == null && ServiceProviderContext.Settings.AllowConsumerRequests) { accessToken = new EmptyAccessToken(context.Consumer.Key); } else if (ServiceProviderContext.TokenStore.ContainsAccessToken(context.Parameters.Token)) { accessToken = ServiceProviderContext.TokenStore.GetAccessToken(context.Parameters.Token); } if (accessToken == null) { OAuthRequestException.ThrowTokenRejected(null); } else { /* * Ensure the token was issued to the same consumer as this request purports * to be from. */ if (!accessToken.ConsumerKey.Equals(context.Parameters.ConsumerKey)) { OAuthRequestException.ThrowTokenRejected(null); } switch (accessToken.Status) { case TokenStatus.Authorized: context.AccessToken = accessToken; break; case TokenStatus.Expired: OAuthRequestException.ThrowTokenExpired(null); break; case TokenStatus.Used: OAuthRequestException.ThrowTokenUsed(null); break; case TokenStatus.Revoked: OAuthRequestException.ThrowTokenRevoked(null); break; case TokenStatus.Unauthorized: case TokenStatus.Unknown: default: OAuthRequestException.ThrowTokenRejected(null); break; } } }
// Checks whether the supplied nonce, timestamp and consumer key combination is unique within // the current window. protected virtual RequestId ValidateNonce(string nonce, long timestamp, string consumerKey, string token) { RequestId currentId = new RequestId(timestamp, nonce, consumerKey, token); bool foundClash = false; // Lock the request cache while we look for the current id lock (SyncRoot) { if (this.RequestCache.ContainsKey(currentId.Timestamp)) { // Get all requests with the same timestamp IList <RequestId> requests = this.RequestCache[currentId.Timestamp]; foreach (RequestId request in requests) { if (request == currentId) { foundClash = true; break; } } } // If we didn't find a clash, store the current id in the cache if (!foundClash) { if (!this.RequestCache.ContainsKey(currentId.Timestamp)) { this.RequestCache[currentId.Timestamp] = new List <RequestId>(); } this.RequestCache[currentId.Timestamp].Add(currentId); } } // If we did find a clash, throw a nonce used OAuthRequestException if (foundClash) { OAuthRequestException.ThrowNonceUsed(null); } return(currentId); }
private OAuthResponse GetResource(NameValueCollection parameters, string contentType, System.IO.Stream bodyStream) { OAuthResponse response; HttpWebRequest request = this.PrepareProtectedResourceRequest(parameters, contentType, bodyStream); // A null value for the HttpWebRequest is returned when a ResponseToken is returned // and no one has returned in the AuthorizationHandler continue with getting an AccessToken // or an RequestToken exists but the AccessToken request was refused. if (request == null) { response = new OAuthResponse(this.RequestToken); } else { OAuthResource resource; OAuthParameters responseParameters; try { resource = new OAuthResource((HttpWebResponse)request.GetResponse()); // Parse the parameters and re-throw any OAuthRequestException from the service provider responseParameters = OAuthParameters.Parse(resource); OAuthRequestException.TryRethrow(responseParameters); // If nothing is thrown then we should have a valid resource. response = new OAuthResponse(this.AccessToken ?? this.RequestToken, resource); } catch (WebException e) { // Parse the parameters and re-throw any OAuthRequestException from the service provider responseParameters = OAuthParameters.Parse(e.Response as HttpWebResponse); OAuthRequestException.TryRethrow(responseParameters); // If no OAuthRequestException, rethrow the WebException #warning TODO: We have consumer the WebException's body so rethrowing it is pretty pointless; wrap the WebException in an OAuthProtocolException and store the body (create an OAuthResource before parsing parameters) throw; } } return(response); }
// Checks whether the supplied timestamp falls within the window of valid timestamps. The // window of valid timestamps is +/- (window / 2) seconds from the current // server time. // // Returns the timestamp as an integer if it is ok, or throw an OAuthRequestException if it // not ok protected virtual long ValidateTimestamp(string timestampValue, long now) { long timestamp; // Parse the timestamp (it must be a positive integer) and check // the timestamp is within +/ HalfWindow from the current time if (!long.TryParse(timestampValue, out timestamp) || timestamp <= 0 || (now - timestamp) > this.HalfWindow) { OAuthRequestException.ThrowTimestampRefused(now - this.HalfWindow, now + this.HalfWindow, null); } else { return(timestamp); } // We won't get here but the compiler can't know that throw new InvalidOperationException("Should be unreachable code"); }
protected virtual void SignParameters(Uri requestUri, string httpMethod, OAuthParameters authParameters, IToken token) { // Check there is a signing provider for the signature method ISigningProvider signingProvider = this.Service.ComponentLocator.GetInstance <ISigningProvider>(Constants.SigningProviderIdPrefix + this.Service.SignatureMethod); if (signingProvider == null) { // There is no signing provider for this signature method OAuthRequestException.ThrowSignatureMethodRejected(null); } // Double check the signing provider declares that it can handle the signature method if (!signingProvider.SignatureMethod.Equals(this.Service.SignatureMethod)) { OAuthRequestException.ThrowSignatureMethodRejected(null); } // Compute the signature authParameters.Sign(requestUri, httpMethod, this.Service.Consumer, token, signingProvider); }
public static void SetConsumer(OAuthRequestContext context) { /* * Get the consumer by its consumer key */ if (ServiceProviderContext.ConsumerStore.Contains(context.Parameters.ConsumerKey)) { IConsumer consumer = ServiceProviderContext.ConsumerStore.GetByKey(context.Parameters.ConsumerKey); if (consumer == null) { OAuthRequestException.ThrowConsumerKeyUnknown(null); } else { switch (consumer.Status) { case ConsumerStatus.Valid: context.Consumer = consumer; break; case ConsumerStatus.TemporarilyDisabled: OAuthRequestException.ThrowConsumerKeyRefused(null); break; case ConsumerStatus.PermanentlyDisabled: OAuthRequestException.ThrowConsumerKeyRejected(null); break; case ConsumerStatus.Unknown: default: OAuthRequestException.ThrowConsumerKeyUnknown(null); break; } } } else { OAuthRequestException.ThrowConsumerKeyUnknown(null); } }
private void HandleError(object sender, EventArgs e) { if (ServiceProviderContext.Settings.AuthenticateRequests) { HttpApplication application = (HttpApplication)sender; if (application.Context.Error is OAuthRequestException) { OAuthRequestException exception = (OAuthRequestException)application.Context.Error; OAuthRequestContext context = WorkflowHelper.RetrieveOAuthContext(application.Context); if (context != null) { context.AddError(exception); } application.Context.ClearError(); // Ensure we clear the exception to avoid ASP.NET handling this WorkflowHelper.SendBadRequest(application.Context, exception, null); } } }
public static void SetSignature(HttpContext httpContext, OAuthRequestContext requestContext) { // Get the token to sign with string tokenSecret; if (requestContext.AccessToken != null) { tokenSecret = requestContext.AccessToken.Secret; } else if (requestContext.RequestToken != null) { tokenSecret = requestContext.RequestToken.Secret; } else { tokenSecret = null; } /* * Check the signature */ bool isValid = requestContext.SigningProvider.CheckSignature( SignatureBase.Create( httpContext.Request.HttpMethod, new Uri(httpContext.Request.Url.GetLeftPart(UriPartial.Authority) + httpContext.Request.RawUrl), requestContext.Parameters), requestContext.Parameters.Signature, requestContext.Consumer.Secret, tokenSecret); if (!isValid) { OAuthRequestException.ThrowSignatureInvalid(null); } else { requestContext.IsSignatureValid = true; } }
protected virtual void IssueRequestToken(HttpContext httpContext, OAuthRequestContext requestContext) { // Generate a request token IRequestToken token = this.GenerateRequestToken(httpContext, requestContext); // Check to see if the request for a token is oob and that oob is allowed. if (requestContext.Parameters.Callback.Equals(Constants.OAuthOutOfBandCallback)) { if (ServiceProviderContext.Settings.AllowOutOfBandCallback == false) { OAuthRequestException.ThrowParametersRejected(new string[] { Constants.CallbackParameter }, "Out of band is not supported."); } } else { Uri callbackUri; if (Uri.TryCreate(requestContext.Parameters.Callback, UriKind.Absolute, out callbackUri)) { ServiceProviderContext.CallbackStore.AddCallback(token, callbackUri); } else { OAuthRequestException.ThrowParametersRejected(new string[] { Constants.CallbackParameter }, "Not a valid Uri."); } } // Store the token requestContext.RequestToken = token; ServiceProviderContext.TokenStore.Add(token); // Add to the response requestContext.ResponseParameters[Constants.CallbackConfirmedParameter] = "true"; // The spec never defines when to send false or what will happen if you do. requestContext.ResponseParameters[Constants.TokenParameter] = token.Token; requestContext.ResponseParameters[Constants.TokenSecretParameter] = token.Secret; }
/// <summary> /// Authorize the request token for the specified user. /// </summary> /// <param name="token">The request token to authorize</param> /// <param name="authenticatedUser">The user (must be authenticated)</param> /// <returns><c>true</c>, if the token was authorized; /// <c>false</c>, if the token could not be authorized</returns> /// <exception cref="OAuth.Net.Common.OAuthRequestException"> /// If there is a problem with the request that prevents access being granted. /// </exception> public static bool GrantAccess(IRequestToken token, IIdentity authenticatedUser) { if (token == null) { throw new ArgumentNullException("token"); } if (authenticatedUser == null) { throw new ArgumentNullException("authenticatedUser"); } if (!authenticatedUser.IsAuthenticated) { throw new ArgumentException("User must be authenticated", "authenticatedUser"); } switch (token.Status) { case TokenStatus.Authorized: break; case TokenStatus.Expired: OAuthRequestException.ThrowTokenExpired(null); break; case TokenStatus.Revoked: OAuthRequestException.ThrowTokenRevoked(null); break; case TokenStatus.Used: OAuthRequestException.ThrowTokenUsed(null); break; case TokenStatus.Unknown: OAuthRequestException.ThrowTokenRejected(null); break; case TokenStatus.Unauthorized: break; default: throw new ArgumentException("Token status is invalid", "token"); } if (token.ConsumerKey == null) { OAuthRequestException.ThrowTokenRejected("Token must have a consumer key"); } IConsumer consumer = ServiceProviderContext.ConsumerStore.GetByKey(token.ConsumerKey); if (consumer == null) { OAuthRequestException.ThrowConsumerKeyUnknown("Consumer is unknown"); } switch (consumer.Status) { case ConsumerStatus.TemporarilyDisabled: OAuthRequestException.ThrowConsumerKeyRefused("Consumer is temporarily disabled"); break; case ConsumerStatus.PermanentlyDisabled: OAuthRequestException.ThrowConsumerKeyRejected("Consumer is permanently disabled"); break; case ConsumerStatus.Valid: break; case ConsumerStatus.Unknown: OAuthRequestException.ThrowConsumerKeyUnknown("Consumer is unknown"); break; default: throw new ArgumentException("Token consumer's status is invalid", "token"); } token.Status = TokenStatus.Authorized; token.AuthenticatedUser = authenticatedUser; if (ServiceProviderContext.TokenStore.Update(token)) { return(true); } else { token.Status = TokenStatus.Unauthorized; token.AuthenticatedUser = null; return(false); } }
public void RemoveError(OAuthRequestException error) { this.errors.Remove(error); }
public void AddError(OAuthRequestException error) { this.errors.Add(error); }
private void OAuthRequestExceptionToBearerTokenUsageError(ExceptionContext context, OAuthRequestException oAuthRequestException) { var headerValues = new List <string> { IdentityConstants.TokenTypes.Bearer, oAuthRequestException.Error }; if (!oAuthRequestException.ErrorDescription.IsNullOrWhiteSpace()) { headerValues.Add(oAuthRequestException.ErrorDescription); } context.HttpContext.Response.Headers.Add(HeaderNames.WWWAuthenticate, new StringValues(headerValues.ToArray())); context.Result = new UnauthorizedResult(); }
protected virtual bool DoGetAccessToken() { // Fire the OnBeforeGetAccessToken event PreAccessTokenRequestEventArgs preArgs = new PreAccessTokenRequestEventArgs( this.Service.AccessTokenUrl, this.Service.AccessTokenEndPoint.HttpMethod, this.RequestToken, this.RequestTokenVerifier); if (this.OnBeforeGetAccessToken != null) { this.OnBeforeGetAccessToken(this, preArgs); } // Create and sign the request OAuthParameters authParams = this.CreateOAuthParameters(null); authParams.Verifier = preArgs.Verifier; // We don't have a verifier so something has gone wrong in the process. if (string.IsNullOrEmpty(authParams.Verifier)) { return(false); } this.SignParameters(preArgs.RequestUri, preArgs.HttpMethod, authParams, this.RequestToken); HttpWebRequest request = this.CreateRequest( preArgs.RequestUri, authParams, preArgs.HttpMethod, preArgs.HttpMethod == "POST" ? Constants.HttpPostUrlEncodedContentType : String.Empty, null); HttpWebResponse response = null; OAuthParameters responseParameters = null; // Get the service provider response try { response = (HttpWebResponse)request.GetResponse(); // Parse the parameters and re-throw any OAuthRequestException from the service provider responseParameters = OAuthParameters.Parse(response); OAuthRequestException.TryRethrow(responseParameters); } catch (WebException e) { // Parse the parameters and re-throw any OAuthRequestException from the service provider responseParameters = OAuthParameters.Parse(e.Response as HttpWebResponse); OAuthRequestException.TryRethrow(responseParameters); // If no OAuthRequestException, rethrow the WebException throw; } // Store the access token this.AccessToken = new OAuthToken( TokenType.Access, responseParameters.Token, responseParameters.TokenSecret, this.Service.Consumer); // Fire the OnReceiveAccessToken event AccessTokenReceivedEventArgs responseArgs = new AccessTokenReceivedEventArgs( this.RequestToken, this.AccessToken, responseParameters.AdditionalParameters); if (this.OnReceiveAccessToken != null) { this.OnReceiveAccessToken(this, responseArgs); } return(true); }
protected virtual void DoGetRequestToken() { // Fire the OnBeforeGetRequestToken event PreRequestEventArgs args = new PreRequestEventArgs( this.Service.RequestTokenUrl, this.Service.RequestTokenEndPoint.HttpMethod, this.CallbackUrl, new NameValueCollection()); if (this.OnBeforeGetRequestToken != null) { this.OnBeforeGetRequestToken(this, args); } OAuthParameters authParams = this.CreateOAuthParameters(args.AdditionalParameters); authParams.Callback = args.CallbackUrl == null ? Constants.OAuthOutOfBandCallback : args.CallbackUrl.AbsoluteUri; this.SignParameters(args.RequestUri, args.HttpMethod, authParams, null); // Create and sign the request HttpWebRequest request = this.CreateRequest( args.RequestUri, authParams, args.HttpMethod, args.HttpMethod == "POST" ? Constants.HttpPostUrlEncodedContentType : String.Empty, null); HttpWebResponse response = null; OAuthParameters responseParameters = null; // Get the service provider response try { response = (HttpWebResponse)request.GetResponse(); // Parse the parameters and re-throw any OAuthRequestException from the service provider responseParameters = OAuthParameters.Parse(response); OAuthRequestException.TryRethrow(responseParameters); } catch (WebException e) { // Parse the parameters and re-throw any OAuthRequestException from the service provider responseParameters = OAuthParameters.Parse(e.Response as HttpWebResponse); OAuthRequestException.TryRethrow(responseParameters); // If no OAuthRequestException, rethrow the WebException throw; } // Store the request token this.RequestToken = new OAuthToken( TokenType.Request, responseParameters.Token, responseParameters.TokenSecret, this.Service.Consumer); // Fire the OnReceiveRequestToken event RequestTokenReceivedEventArgs responseArgs = new RequestTokenReceivedEventArgs( this.RequestToken, responseParameters.AdditionalParameters); if (this.OnReceiveRequestToken != null) { this.OnReceiveRequestToken(this, responseArgs); } }