protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.Headers.Authorization != null) { if (request.Headers.Authorization.Scheme == "Bearer") { //If there are authorization headers that use the Bearer token scheme, try to digest the token and, if available, //set the current user context. try { var AuthServerPublicKey = (RSACryptoServiceProvider)AuthorizationServerHost.AuthorizationServerCertificate.PublicKey.Key; var ResourceServerPrivateKey = (RSACryptoServiceProvider)AuthorizationServerHost.ResourceServerCertificate.PrivateKey; var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AuthServerPublicKey, ResourceServerPrivateKey)); var principal = resourceServer.GetPrincipal(request); HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; } catch (ProtocolFaultResponseException ex) { //A protocol fault response exception is thrown in the case that a client cannot be properly authenticated by the provided //token. To diagnose any errors you may be getting, you can re-throw or log ex.ErrorResponseMessage. //For now, let's just inform the client that they're unauthorized for this resource. SendUnauthorizedResponse(); } } } else { //This API does not allow unauthenticated access, return an unauthorized status code. SendUnauthorizedResponse(); } return base.SendAsync(request, cancellationToken); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpContextBase httpContext; string userName; HashSet<string> scope; if (!request.TryGetHttpContext(out httpContext)) throw new InvalidOperationException("HttpContext must not be null."); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer( (RSACryptoServiceProvider)_configuration.IssuerSigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)_configuration.EncryptionVerificationCertificate.PrivateKey)); var error = resourceServer.VerifyAccess(httpContext.Request, out userName, out scope); if (error != null) return Task<HttpResponseMessage>.Factory.StartNew(error.ToHttpResponseMessage); Microsoft.IdentityModel.Claims.ClaimsIdentity identity = new Microsoft.IdentityModel.Claims.ClaimsIdentity(scope.Select(s => new Microsoft.IdentityModel.Claims.Claim(s, s))); if (!string.IsNullOrEmpty(userName)) identity.Claims.Add(new Microsoft.IdentityModel.Claims.Claim(Microsoft.IdentityModel.Claims.ClaimTypes.Name, userName)); httpContext.User = Microsoft.IdentityModel.Claims.ClaimsPrincipal.CreateFromIdentity(identity); Thread.CurrentPrincipal = httpContext.User; return base.SendAsync(request, cancellationToken); }
public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { var scopeAttributes = actionContext.ActionDescriptor.GetCustomAttributes<RequireScopeAttribute>(); var resourseServer = new ResourceServer( new StandardAccessTokenAnalyzer(AuthorizationServerHost.HardCodedCryptoKeyStore)) { ScopeSatisfiedCheck = new ScopeSatisfiedCheck() }; string[] scopes = { }; if (scopeAttributes.Any()) { scopes = scopeAttributes[0].Scopes; } try { var principal = await resourseServer.GetPrincipalAsync(actionContext.Request, cancellationToken, requiredScopes: scopes); HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; } catch (ProtocolFaultResponseException ex) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } return await continuation(); }
private static async Task<IPrincipal> VerifyOAuth2(HttpRequestMessage httpDetails, params string[] requiredScopes) { // for this sample where the auth server and resource server are the same site, // we use the same public/private key. var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey)); return await resourceServer.GetPrincipalAsync(httpDetails, requiredScopes: requiredScopes); }
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { HttpRequestMessage request = actionContext.Request; HttpContextBase httpContext; string userName; HashSet<string> scope; if (!request.TryGetHttpContext(out httpContext)) throw new InvalidOperationException("HttpContext must not be null."); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer( (RSACryptoServiceProvider)_configuration.IssuerSigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)_configuration.EncryptionVerificationCertificate.PrivateKey)); var error = resourceServer.VerifyAccess(httpContext.Request, out userName, out scope); if (error != null) return Task<HttpResponseMessage>.Factory.StartNew(error.ToHttpResponseMessage); //var identity = new ClaimsIdentity(scope.Select(s => new Claim(s, s))); //if (!string.IsNullOrEmpty(userName)) // identity.AddClaim(new Claim(ClaimTypes.Name, userName)); //httpContext.User = new GenericPrincipal(identity, null); //Thread.CurrentPrincipal = httpContext.User; return continuation(); }
/// <summary> /// Handles the AuthenticateRequest event of the HttpApplication. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void context_AuthenticateRequest(object sender, EventArgs e) { // Don't read OAuth messages directed at the OAuth controller or else we'll fail nonce checks. if (this.IsOAuthControllerRequest()) { return; } using (var crypto = OAuthResourceServer.CreateRSA()) { var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto); var resourceServer = new ResourceServer(tokenAnalyzer); var context = this.application.Context; Task.Run( async delegate { ProtocolFaultResponseException exception = null; try { IPrincipal principal = await resourceServer.GetPrincipalAsync(new HttpRequestWrapper(context.Request)); context.User = principal; return; } catch (ProtocolFaultResponseException ex) { exception = ex; } var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None); await errorResponse.SendAsync(); }).Wait(); } }
public void GetPrincipalWithMissingAccessToken() { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); var requestHeaders = new NameValueCollection { { "Authorization", "Bearer " }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); Assert.That(() => resourceServer.GetPrincipalAsync(request).GetAwaiter().GetResult(), Throws.InstanceOf<ProtocolException>()); }
public void GetAccessTokenWithTotallyFakeToken() { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); var requestHeaders = new NameValueCollection { { "Authorization", "Bearer foobar" }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); Assert.That(() => resourceServer.GetAccessToken(request), Throws.InstanceOf<ProtocolException>()); }
private async Task <IPrincipal> ValidateToken(HttpRequestMessage request, params string[] scopes) { var signPublicKey = (RSACryptoServiceProvider)ResourceServerConfiguration.Default.SigningCertificate.PublicKey.Key; var encryptPrivateKey = (RSACryptoServiceProvider)ResourceServerConfiguration.Default.EncryptionCertificate.PrivateKey; var tokenAnalyzer = new StandardAccessTokenAnalyzer(signPublicKey, encryptPrivateKey); var resourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(tokenAnalyzer); return(await resourceServer.GetPrincipalAsync(request, requiredScopes : scopes)); }
private static async Task<IPrincipal> VerifyOAuth2Async(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes) { // for this sample where the auth server and resource server are the same site, // we use the same public/private key. using (var signing = Global.CreateAuthorizationServerSigningServiceProvider()) { using (var encrypting = Global.CreateResourceServerEncryptionServiceProvider()) { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(signing, encrypting)); return await resourceServer.GetPrincipalAsync(httpDetails, requestUri, requiredScopes: requiredScopes); } } }
public void GetAccessTokenWithCorruptedToken() { var accessToken = this.ObtainValidAccessToken(); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); var requestHeaders = new NameValueCollection { { "Authorization", "Bearer " + accessToken.Substring(0, accessToken.Length - 1) + "zzz" }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); Assert.That(() => resourceServer.GetAccessToken(request), Throws.InstanceOf<ProtocolException>()); }
public override void OnAuthorization(HttpActionContext actionContext) { try { base.OnAuthorization(actionContext); // Bail if no auth header or the header isn't bearing a token for us var authHeader = actionContext.Request.Headers.FirstOrDefault(x => x.Key == "Authorization"); if (authHeader.Value == null || !authHeader.Value.Any()) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } var authHeaderValue = authHeader.Value.FirstOrDefault(x => x.StartsWith("Bearer ")); if (authHeaderValue == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } // Have the DotNetOpenAuth resource server inspect the provided request using the configured keys // This checks both that the token is ok and that the token grants the scope required by // the required scope parameters to this attribute var resourceServer = new DNOA.ResourceServer(new StandardAccessTokenAnalyzer(SignatureVerifier, Decrypter)); var principal = resourceServer.GetPrincipal(actionContext.Request,RequiredScopes); if (principal != null) { // Things look good. Set principal for the resource to use in identifying the user so it can act accordingly Thread.CurrentPrincipal = principal; HttpContext.Current.User = principal; // Dont understand why the call to GetPrincipal is setting actionContext.Response to be unauthorized // even when the principal returned is non-null // If I do this code the same way in a delegating handler, that doesn't happen actionContext.Response = null; } else { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } } catch (SecurityTokenValidationException) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } catch (ProtocolFaultResponseException) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } catch (Exception) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest); } }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.Headers.Authorization != null) { if (request.Headers.Authorization.Scheme == "Bearer") { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AuthorizationServerHost.HardCodedCryptoKeyStore)); var principal = await resourceServer.GetPrincipalAsync(request, cancellationToken); HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; } } return await base.SendAsync(request, cancellationToken); }
public override void OnAuthorization(HttpActionContext actionContext) { try { base.OnAuthorization(actionContext); // Bail if no auth header or the header isn't bearing a token for us var authHeader = actionContext.Request.Headers.FirstOrDefault(x => x.Key == "Authorization"); if (authHeader.Value == null || !authHeader.Value.Any()) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } var authHeaderValue = authHeader.Value.FirstOrDefault(x => x.StartsWith("Bearer ")); if (authHeaderValue == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } // Have the DotNetOpenAuth resource server inspect the provided request using the configured keys // This checks both that the token is ok and that the token grants the scope required by // the required scope parameters to this attribute var resourceServer = new DNOA.ResourceServer(new StandardAccessTokenAnalyzer(SignatureVerifier, Decrypter)); var principal = resourceServer.GetPrincipal(actionContext.Request, RequiredScopes); if (principal != null) { // Things look good. Set principal for the resource to use in identifying the user so it can act accordingly Thread.CurrentPrincipal = principal; HttpContext.Current.User = principal; // Dont understand why the call to GetPrincipal is setting actionContext.Response to be unauthorized // even when the principal returned is non-null // If I do this code the same way in a delegating handler, that doesn't happen actionContext.Response = null; } else { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } } catch (SecurityTokenValidationException) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } catch (ProtocolFaultResponseException) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } catch (Exception) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest); } }
public void GetAccessTokenWithValidToken() { var accessToken = this.ObtainValidAccessToken(); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); var requestHeaders = new NameValueCollection { { "Authorization", "Bearer " + accessToken }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); var resourceServerDecodedToken = resourceServer.GetAccessToken(request); Assert.That(resourceServerDecodedToken, Is.Not.Null); }
public override void Execute(IHttpRequest request, IHttpResponse response, object requestDto) { try { var authServerKeys = AppHostBase.Instance.Container.ResolveNamed <ICryptoKeyPair>("authServer"); var dataServerKeys = AppHostBase.Instance.Container.ResolveNamed <ICryptoKeyPair>("dataServer"); var tokenAnalyzer = new StandardAccessTokenAnalyzer(authServerKeys.PublicSigningKey, dataServerKeys.PrivateEncryptionKey); var oauth2ResourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(tokenAnalyzer); var wrappedRequest = new HttpRequestWrapper((HttpRequest)request.OriginalRequest); HttpContext.Current.User = oauth2ResourceServer.GetPrincipal(wrappedRequest, oauth2Scopes); } catch (ProtocolFaultResponseException x) { HandleOAuth2Exception(request, response, x); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { var rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(Convert.FromBase64String(ConfigurationManager.AppSettings["PrivateAsymmetricKey"])); var analyzer = new StandardAccessTokenAnalyzer(rsa, rsa); var resourceServer = new ResourceServer(analyzer); try { httpContext.User = resourceServer.GetPrincipal( httpContext.Request, this.Roles.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); } catch (ProtocolException) { httpContext.User = null; } return httpContext.User != null; }
private static IPrincipal VerifyOAuth2(HttpRequestMessageProperty httpDetails, Uri requestUri) { // for this sample where the auth server and resource server are the same site, // we use the same public/private key. using (var signing = Global.CreateAuthorizationServerSigningServiceProvider()) { using (var encrypting = Global.CreateResourceServerEncryptionServiceProvider()) { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(signing, encrypting)); IPrincipal result; var error = resourceServer.VerifyAccess(new HttpRequestInfo(httpDetails, requestUri), out result); // TODO: return the prepared error code. return error != null ? null : result; } } }
/// <summary> /// Handles the AuthenticateRequest event of the HttpApplication. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void context_AuthenticateRequest(object sender, EventArgs e) { // Don't read OAuth messages directed at the OAuth controller or else we'll fail nonce checks. if (this.IsOAuthControllerRequest()) { return; } using (var crypto = OAuthResourceServer.CreateRSA()) { var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto); var resourceServer = new ResourceServer(tokenAnalyzer); IPrincipal principal; var errorMessage = resourceServer.VerifyAccess(new HttpRequestInfo(this.application.Context.Request), out principal); if (errorMessage == null) { this.application.Context.User = principal; } } }
protected override bool CheckAccessCore(OperationContext operationContext) { if (!base.CheckAccessCore(operationContext)) { return false; } var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via; using (var crypto = OAuthAuthorizationServer.CreateAsymmetricKeyServiceProvider()) { var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto); var resourceServer = new ResourceServer(tokenAnalyzer); try { IPrincipal principal; var errorResponse = resourceServer.VerifyAccess(httpDetails, requestUri, out principal); if (errorResponse == null) { var policy = new OAuthPrincipalAuthorizationPolicy(principal); var policies = new List<IAuthorizationPolicy> { policy, }; var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); if (operationContext.IncomingMessageProperties.Security != null) { operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; } else { operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { ServiceSecurityContext = securityContext, }; } securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, }; // Only allow this method call if the access token scope permits it. if (principal.IsInRole(operationContext.IncomingMessageHeaders.Action)) { return true; } } } catch (ProtocolException /*ex*/) { ////Logger.Error("Error processing OAuth messages.", ex); } } return false; }
protected override bool CheckAccessCore(OperationContext operationContext) { if (!base.CheckAccessCore(operationContext)) { return false; } var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via; return Task.Run( async delegate { using (var crypto = OAuthResourceServer.CreateRSA()) { var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto); var resourceServer = new ResourceServer(tokenAnalyzer); ProtocolFaultResponseException exception = null; try { IPrincipal principal = await resourceServer.GetPrincipalAsync(httpDetails, requestUri, CancellationToken.None, operationContext.IncomingMessageHeaders.Action); var policy = new OAuthPrincipalAuthorizationPolicy(principal); var policies = new List<IAuthorizationPolicy> { policy, }; var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); if (operationContext.IncomingMessageProperties.Security != null) { operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; } else { operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { ServiceSecurityContext = securityContext, }; } securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, }; return true; } catch (ProtocolFaultResponseException ex) { // Return the appropriate unauthorized response to the client. exception = ex; } catch (DotNetOpenAuth.Messaging.ProtocolException /* ex*/) { ////Logger.Error("Error processing OAuth messages.", ex); } var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None); await errorResponse.SendAsync(); } return false; }).Result; }
public override void OnAuthorization(HttpActionContext actionContext) { try { var tokenAnalyzer = new StandardAccessTokenAnalyzer( AuthServer.PublicSigningKey, DataServer.PrivateEncryptionKey); var oauth2ResourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(tokenAnalyzer); ((ApiController)actionContext.ControllerContext.Controller).User = oauth2ResourceServer.GetPrincipal(actionContext.Request.GetRequestBase(), _oauth2Scopes) as PlayerPrincipal; } catch (ProtocolFaultResponseException ex) { HandleUnauthorizedRequest(actionContext, ex); } }
public override async void OnActionExecuting(HttpActionContext actionContext) { // we must have either WWW-Authorize header or access_token parameter to proceed if (actionContext.Request.Headers.Authorization == null && !actionContext.Request.Properties.ContainsKey("access_token")) { actionContext.Response = BuildBearerAuthorizeResponse(HttpStatusCode.BadRequest); } else { try { var resourceServer = new ResourceServer( new StandardAccessTokenAnalyzer(OAuth2AuthorizationServerHost.HardCodedCryptoKeyStore)); // validate token againt a revocation list var accessToken = await resourceServer.GetAccessTokenAsync(actionContext.Request); var lastRevoke = OAuth2AuthorizationServerHost.ClientRevokes .Where(c => c.ClientIdentifier == accessToken.ClientIdentifier) .OrderByDescending(t => t.RevokeTime) .FirstOrDefault(); if (lastRevoke != null && lastRevoke.RevokeTime > accessToken.UtcIssued) { actionContext.Response = BuildBearerAuthorizeResponse(HttpStatusCode.Unauthorized, "invalid_token", "The access token has been revoked"); } else { // get principal var principal = await resourceServer.GetPrincipalAsync(actionContext.Request); HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; } } catch (ProtocolException pe) { actionContext.Response = BearerHttpResponseMessageError(pe); } catch (Exception) // need to handle all exceptions to ensure resource isn't returned { actionContext.Response = BuildBearerAuthorizeResponse(HttpStatusCode.InternalServerError); } } base.OnActionExecuting(actionContext); }
/// <summary> /// Handles the AuthenticateRequest event of the HttpApplication. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void context_AuthenticateRequest(object sender, EventArgs e) { // Don't read OAuth messages directed at the OAuth controller or else we'll fail nonce checks. if (this.IsOAuthControllerRequest()) { return; } using (var crypto = OAuthResourceServer.CreateRSA()) { var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto); var resourceServer = new ResourceServer(tokenAnalyzer); try { IPrincipal principal = resourceServer.GetPrincipal(new HttpRequestWrapper(this.application.Context.Request)); this.application.Context.User = principal; } catch (ProtocolFaultResponseException ex) { ex.CreateErrorResponse().Send(); } } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { bool isAuthorized = false; try { HttpRequestBase request = httpContext.Request; if (!string.IsNullOrEmpty(request.Headers["Authorization"])) { if (request.Headers["Authorization"].StartsWith("Bearer ")) { RSACryptoServiceProvider authorizationServerSigningPublicKey = AuthorizationServerHost.CreateRsaCryptoServiceProvider(AuthorizationServerHost.AuthorizationServerSigningPublicKey); RSACryptoServiceProvider resourceServerEncryptionPrivateKey = AuthorizationServerHost.CreateRsaCryptoServiceProvider(AuthorizationServerHost.ResourceServerEncryptionPrivateKey); StandardAccessTokenAnalyzer tokenAnalyzer = new StandardAccessTokenAnalyzer(authorizationServerSigningPublicKey, resourceServerEncryptionPrivateKey); ResourceServer resourceServer = new ResourceServer(tokenAnalyzer); IPrincipal principal = resourceServer.GetPrincipal(request); if (principal.Identity.IsAuthenticated) { HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; isAuthorized = true; } var _token = resourceServer.GetAccessToken(request); if (this.RequiredScopes.Any()) { var token = resourceServer.GetAccessToken(request, this.RequiredScopes); } } } } catch { isAuthorized = false; } return isAuthorized; }
public static IPrincipal VerifyOAuth2(HttpRequestMessage requestMessage, params string[] requiredScopes) { // for this sample where the auth server and resource server are the same site, // we use the same public/private key. try { using (RSACryptoServiceProvider authorizationRas = AuthorizationServerHelper.CreateAuthorizationServerSigningServiceProvider()) { using (RSACryptoServiceProvider resourceRas = ResourceServerHelper.CreateResourceServerEncryptionServiceProvider()) { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(authorizationRas, resourceRas)); return resourceServer.GetPrincipal(requestMessage);//, requiredScopes 这一版先不验证scope } } } catch (ProtocolFaultResponseException ex)//处理password auth方式授权过期,暂时没找合适的处理入口 { return null; } }
/// <summary> /// Initializes a new instance of the <see cref="OAuthAuthorizeAttribute"/> class. /// </summary> public OAuthAuthorizeAttribute() { var standardAccessTokenAnalyzer = new StandardAccessTokenAnalyzer(EncryptionKeys.GetAuthorizationServerSigningPublicKey(), EncryptionKeys.GetResourceServerEncryptionPrivateKey()); this.resourceServer = new ResourceServer(standardAccessTokenAnalyzer); }
private static async Task<IPrincipal> VerifyOAuth2Async(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes) { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey)); return await resourceServer.GetPrincipalAsync(httpDetails, requestUri, requiredScopes: requiredScopes); }
public override void Execute(IHttpRequest request, IHttpResponse response, object requestDto) { try { var authServerKeys = AppHostBase.Instance.Container.ResolveNamed<ICryptoKeyPair>("authServer"); var dataServerKeys = AppHostBase.Instance.Container.ResolveNamed<ICryptoKeyPair>("dataServer"); var tokenAnalyzer = new StandardAccessTokenAnalyzer(authServerKeys.PublicSigningKey, dataServerKeys.PrivateEncryptionKey); var oauth2ResourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(tokenAnalyzer); var wrappedRequest = new HttpRequestWrapper((HttpRequest)request.OriginalRequest); HttpContext.Current.User = oauth2ResourceServer.GetPrincipal(wrappedRequest, oauth2Scopes); } catch (ProtocolFaultResponseException x) { HandleOAuth2Exception(request, response, x); } }