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);
 }
		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.GetPrincipal(request), Throws.InstanceOf<ProtocolException>());
		}
		private static IPrincipal VerifyOAuth2(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 resourceServer.GetPrincipal(httpDetails, requestUri, requiredScopes);
				}
			}
		}
        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);
            }
        }
Esempio n. 5
0
        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);
            }
        }
Esempio n. 6
0
 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);
     }
 }
Esempio n. 7
0
		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;
		}
 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);
     }
 }
		/// <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 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 = OAuthResourceServer.CreateRSA()) {
				var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto);
				var resourceServer = new ResourceServer(tokenAnalyzer);

				try {
					IPrincipal principal = resourceServer.GetPrincipal(httpDetails, requestUri, 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.
					ex.CreateErrorResponse().Send();
				} catch (DotNetOpenAuth.Messaging.ProtocolException/* ex*/) {
					////Logger.Error("Error processing OAuth messages.", ex);
				}
			}

			return false;
		}
Esempio n. 11
0
        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;
     }
 }
 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);
     }
 }