public OAuthServiceCall(HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            OriginalRequest  = request;
            ServiceCall      = ServiceFromString(request.PathInfo);
            ResponseCallback = util.GetStringParam(request, "callback");
            ResultFormat     = (util.GetIntParam(request, "json", 0) != 0) ? (String.IsNullOrEmpty(ResponseCallback) ? OutputFormat.JSON : OutputFormat.JSONP) : OutputFormat.XML;

            using (RSACryptoServiceProvider rsaSigning = new RSACryptoServiceProvider())
            {
                using (RSACryptoServiceProvider rsaEncryption = new RSACryptoServiceProvider())
                {
                    rsaSigning.ImportParameters(OAuth2AuthorizationServer.AuthorizationServerSigningPublicKey);
                    rsaEncryption.ImportParameters(OAuth2AuthorizationServer.CreateAuthorizationServerSigningKey());
                    ResourceServer server = new ResourceServer(new StandardAccessTokenAnalyzer(rsaSigning, rsaEncryption));
                    Token = server.GetAccessToken();

                    if (Token.Lifetime.HasValue && Token.UtcIssued.Add(Token.Lifetime.Value).CompareTo(DateTime.UtcNow) < 0)
                    {
                        throw new MyFlightbookException("oAuth2 - Token has expired!");
                    }
                    if (String.IsNullOrEmpty(Token.User))
                    {
                        throw new MyFlightbookException("Invalid oAuth token - no user");
                    }

                    GeneratedAuthToken = MFBWebService.AuthTokenFromOAuthToken(Token);
                }
            }
        }
        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);
            }
        }
Example #3
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 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>());
        }
        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 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);
        }
Example #7
0
 public static bool AuthUser(HttpRequestMessage request)
 {
     using (RSACryptoServiceProvider authorizationServerRsa = GetAuthorizationServerRsa())
     {
         using (RSACryptoServiceProvider resourceServerRsa = GetResourceServerRsa())
         {
             ResourceServer resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(authorizationServerRsa, resourceServerRsa));
             var            token          = resourceServer.GetAccessToken(request, new string[0]);
             if (token != null)
             {
                 IPrincipal principal = CreatePrincipal(token.User);
                 HttpContext.Current.User = principal;
                 Thread.CurrentPrincipal  = principal;
                 request.Headers.Add("UserName", token.User);
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
     }
 }
Example #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);
            }
        }