public override void Execute(IRequest request, IResponse response, object requestDto)
        {
            try
            {
                var            cryptoKeyProvider = ServiceStackHost.Instance.Container.Resolve <ICryptoKeyProvider>();
                ICryptoKeyPair authZServerKeys   = cryptoKeyProvider.GetCryptoKey(CryptoKeyType.AuthZServer);
                ICryptoKeyPair apiServiceKeys    = cryptoKeyProvider.GetCryptoKey(CryptoKeyType.ApiService);

                var tokenAnalyzer = new StandardAccessTokenAnalyzer(authZServerKeys.PublicSigningKey,
                                                                    apiServiceKeys.PrivateEncryptionKey);
                var resourceServer = new ResourceServer(tokenAnalyzer);

                // Verify the signed bearer token (for specified scopes), and extract the user's identity
                AccessToken token = resourceServer.GetAccessToken((HttpRequestBase)request.OriginalRequest, scopes);

                // Assign this user to the current HTTP context
                var user = new OAuthPrincipal(token.User, GetUserRoles(token));
                ((HttpRequestBase)request.OriginalRequest).RequestContext.HttpContext.User = user;
            }
            catch (ProtocolFaultResponseException ex)
            {
                //TODO: if the token is invalid in some way (i.e. malformed) then return 400-BadRequest.
                // The token is either: expired or invalid or revoked, we need to return 401-Unauthorized
                response.AddHeader(HttpHeaders.WwwAuthenticate, @"Bearer");
                throw HttpErrorThrower.Unauthorized(ex.Message);
            }
        }
Esempio n. 2
0
        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));
        }
Esempio n. 3
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);
     }
 }
 public override void OnAuthorization(HttpActionContext actionContext)
 {
     try
     {
         var tokenAnalyzer =
             new StandardAccessTokenAnalyzer(
                 AuthServer.PublicSigningKey,
                 DataServer.PrivateEncryptionKey);
         var oauth2ResourceServer = new ResourceServer(tokenAnalyzer);
         ((ApiController)actionContext.ControllerContext.Controller).User =
             oauth2ResourceServer.GetPrincipal(actionContext.Request.GetRequestBase(), _oauth2Scopes) as PlayerPrincipal;
     }
     catch (ProtocolFaultResponseException ex)
     {
         HandleUnauthorizedRequest(actionContext, ex);
     }
 }
Esempio n. 5
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);
        }
Esempio n. 6
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);
        }
Esempio n. 7
0
        /// <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);
        }
Esempio n. 8
0
        /// <summary>
        /// Verify that the request is valid.
        /// </summary>
        /// <param name="httpRequest">The HTTP request base.</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="requiredScopes">The set of scopes required to approve this request.</param>
        /// <returns>
        /// The principal that contains the user and roles that the access token is authorized for; else null.
        /// </returns>
        private IPrincipal Verify(HttpRequestBase httpRequest, Uri rawUri, NameValueCollection queryString,
                                  NameValueCollection form, NameValueCollection headers, params string[] requiredScopes)
        {
            string clientID    = null;
            string nonce       = null;
            string accessToken = null;

            string tokenNonce = null;
            string userID     = 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");
                }

                // Attempt to find the 'access_token' parameter in the form.
                IEnumerable <string> accessTokens = form.AllKeys.Where(u => u.EndsWith("access_token"));
                if (accessTokens == null || accessTokens.Count() < 1)
                {
                    // Attempt to find the 'access_token' parameter in the query string.
                    if (queryString != null || queryString.Keys.Count > 0)
                    {
                        if (queryString["access_token"] != null)
                        {
                            accessToken = queryString["access_token"];
                        }
                    }

                    // Attempt to find the 'access_token' parameter in the headers.
                    if (headers != null || headers.Keys.Count > 0)
                    {
                        if (headers["access_token"] != null)
                        {
                            accessToken = headers["access_token"];
                        }
                    }
                }
                else
                {
                    accessToken = form["access_token"];
                }

                // Pass a access token
                if (!String.IsNullOrEmpty(accessToken))
                {
                    // Get the nonce data for the code value.
                    nonce    = _tokenStore.GetNonceByAccessToken(accessToken);
                    clientID = _consumerStore.GetConsumerIdentifier(nonce);

                    // Make sure that the token is still valid.
                    if (!_consumerStore.IsAuthorizationValid(clientID, nonce))
                    {
                        return(null);
                    }
                    else
                    {
                        // Get the encryption certificate for the client.
                        // Create a new access token decryption analyser.
                        X509Certificate2            certificate         = _consumerStore.GetConsumerCertificate(clientID);
                        StandardAccessTokenAnalyzer accessTokenAnalyzer =
                            new StandardAccessTokenAnalyzer(
                                (RSACryptoServiceProvider)certificate.PrivateKey,
                                (RSACryptoServiceProvider)certificate.PublicKey.Key);

                        // Assign the analyser and get the access token
                        // data from the http request.
                        _resourceServer.AccessTokenAnalyzer = accessTokenAnalyzer;
                        AccessToken token = _resourceServer.GetAccessToken(httpRequest, requiredScopes);

                        // Get the priciple identity of the access token request.
                        IPrincipal principal = _resourceServer.GetPrincipal(token, out userID, out tokenNonce, httpRequest, requiredScopes);
                        return(principal);
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                // Get the current token errors.
                _tokenError = ex.Message;
                return(null);
            }
        }