public virtual TokenResponse CreateTokenResponseFromAuthorizationCode(TokenHandle handle, ITokenHandleManager handleManager)
        {
            var resourceOwner = Principal.Create(
                "OAuth2",
                handle.ResourceOwner.ToClaims().ToArray());

            var validatedRequest = new ValidatedRequest
            {
                Client = handle.Client,
                Application = handle.Application,
                Scopes = handle.Scopes
            };

            var response = CreateTokenResponse(validatedRequest, resourceOwner);

            if (handle.CreateRefreshToken)
            {
                var refreshTokenHandle = TokenHandle.CreateRefreshTokenHandle(
                    resourceOwner.GetSubject(),
                    handle.Client,
                    handle.Application,
                    resourceOwner.Claims,
                    handle.Scopes,
                    handle.RefreshTokenExpiration);

                handleManager.Add(refreshTokenHandle);
                response.RefreshToken = refreshTokenHandle.HandleId;
            }
                
            handleManager.Delete(handle.HandleId);

            return response;
        }
        private HttpResponseMessage ProcessAssertionGrant(ValidatedRequest validatedRequest)
        {
            ClaimsPrincipal principal;

            try
            {
                Tracing.Information("Calling assertion grant handler for assertion: " + validatedRequest.Assertion);
                principal = _assertionGrantValidator.ValidateAssertion(validatedRequest);
            }
            catch (Exception ex)
            {
                Tracing.Error("Unhandled exception in assertion grant handler: " + ex.ToString());
                throw;
            }

            if (principal == null)
            {
                Tracing.Error("Assertion grant handler failed to validate assertion");
                return Request.CreateOAuthErrorResponse(OAuthConstants.Errors.InvalidGrant);
            }

            var sts = new TokenService(_config.GlobalConfiguration);
            var response = sts.CreateTokenResponse(validatedRequest, principal);
            return Request.CreateTokenResponse(response);
        }
        private HttpResponseMessage ProcessClientCredentialsRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing refresh token request");

            var sts = new TokenService(_config.GlobalConfiguration);
            var response = sts.CreateTokenResponse(validatedRequest);
            return Request.CreateTokenResponse(response);
        }
        public virtual TokenResponse CreateTokenResponseFromRefreshToken(TokenHandle handle, ITokenHandleManager handleManager)
        {
            var resourceOwner = Principal.Create(
                "OAuth2",
                handle.ResourceOwner.ToClaims().ToArray());

            var validatedRequest = new ValidatedRequest
            {
                Client = handle.Client,
                Application = handle.Application,
                Scopes = handle.Scopes,
            };

            var response = CreateTokenResponse(validatedRequest, resourceOwner);
            response.RefreshToken = handle.HandleId;
            
            return response;
        }
Пример #5
0
        public virtual TokenResponse CreateTokenResponse(ValidatedRequest request, ClaimsPrincipal resourceOwner = null)
        {
            try
            {
                var claims = CreateClaims(request, resourceOwner);
                var token = CreateToken(request, claims);

                return new TokenResponse
                {
                    AccessToken = WriteToken(token),
                    ExpiresIn = request.Application.TokenLifetime * 60,
                    TokenType = "Bearer"
                };
            }
            catch (Exception ex)
            {
                Tracing.Error(ex.ToString());
                throw;
            }
        }
        private ActionResult PerformGrant(ValidatedRequest validatedRequest)
        {
            // implicit grant
            if (validatedRequest.ResponseType.Equals(OAuthConstants.ResponseTypes.Token, StringComparison.Ordinal))
            {
                return PerformImplicitGrant(validatedRequest);
            }

            // authorization code grant
            if (validatedRequest.ResponseType.Equals(OAuthConstants.ResponseTypes.Code, StringComparison.Ordinal))
            {
                return PerformAuthorizationCodeGrant(validatedRequest);
            }

            return null;
        }
        private ActionResult PerformAuthorizationCodeGrant(ValidatedRequest validatedRequest)
        {
            var handle = StoredGrant.CreateAuthorizationCode(
                validatedRequest.Client,
                validatedRequest.Application,
                validatedRequest.RedirectUri.Uri,
                ClaimsPrincipal.Current.FilterInternalClaims(),
                validatedRequest.Scopes,
                validatedRequest.RequestingRefreshToken,
                validatedRequest.RequestedRefreshTokenExpiration);

            _handleManager.Add(handle);
            var tokenString = string.Format("code={0}", handle.GrantId);

            if (!string.IsNullOrWhiteSpace(validatedRequest.State))
            {
                tokenString = string.Format("{0}&state={1}", tokenString, Server.UrlEncode(validatedRequest.State));
            }

            var redirectString = string.Format("{0}?{1}",
                        validatedRequest.RedirectUri.Uri,
                        tokenString);

            return Redirect(redirectString);
        }
        public ValidatedRequest Validate(Application application, AuthorizeRequest request)
        {
            // If the request fails due to a missing, invalid, or mismatching
            // redirection URI, or if the client identifier is missing or invalid,
            // the authorization server SHOULD inform the resource owner of the
            // error and MUST NOT automatically redirect the user-agent to the
            // invalid redirection URI.

            var validatedRequest = new ValidatedRequest();

            // validate request model binding
            if (request == null)
            {
                throw new AuthorizeRequestResourceOwnerException("Invalid request parameters.");
            }

            validatedRequest.Application = application;
            Tracing.InformationFormat("OAuth2 application: {0} ({1})",
                validatedRequest.Application.Name,
                validatedRequest.Application.Namespace);

            validatedRequest.ShowRememberConsent = application.AllowRememberConsentDecision;

            // make sure redirect uri is present
            if (string.IsNullOrWhiteSpace(request.redirect_uri))
            {
                throw new AuthorizeRequestResourceOwnerException("Missing redirect URI");
            }

            // validate client
            if (string.IsNullOrWhiteSpace(request.client_id))
            {
                throw new AuthorizeRequestResourceOwnerException("Missing client identifier");
            }


            var client = _clientManager.Get(request.client_id);
            if (client == null)
            {
                throw new AuthorizeRequestResourceOwnerException("Invalid client: " + request.client_id);
            }

            validatedRequest.Client = client;
            Tracing.InformationFormat("Client: {0} ({1})",
                validatedRequest.Client.Name,
                validatedRequest.Client.ClientId);

            // make sure redirect_uri is a valid uri, and in case of http is over ssl
            Uri redirectUri;
            if (Uri.TryCreate(request.redirect_uri, UriKind.Absolute, out redirectUri))
            {
                if (redirectUri.Scheme == Uri.UriSchemeHttp)
                {
                    throw new AuthorizeRequestClientException(
                        "Redirect URI not over SSL : " + request.redirect_uri,
                        new Uri(request.redirect_uri),
                        OAuthConstants.Errors.InvalidRequest,
                        string.Empty,
                        validatedRequest.State);
                }

                // make sure redirect uri is registered with client
                var validUri = validatedRequest.Client.RedirectUris.Get(request.redirect_uri);

                if (validUri == null)
                {
                    throw new AuthorizeRequestResourceOwnerException("Invalid redirect URI: " + request.redirect_uri);
                }

                validatedRequest.RedirectUri = validUri;
                Tracing.InformationFormat("Redirect URI: {0} ({1})",
                    validatedRequest.RedirectUri.Uri,
                    validatedRequest.RedirectUri.Description);
            }
            else
            {
                var message = "Invalid redirect URI: " + request.redirect_uri;
                Tracing.Error(message);

                throw new AuthorizeRequestResourceOwnerException("Invalid redirect URI: " + request.redirect_uri);
            }

            // check state
            if (!string.IsNullOrWhiteSpace(request.state))
            {
                validatedRequest.State = request.state;
                Tracing.Information("State: " + validatedRequest.State);
            }
            else
            {
                Tracing.Information("No state supplied.");
            }

            // validate response type
            if (String.IsNullOrWhiteSpace(request.response_type))
            {
                throw new AuthorizeRequestClientException(
                    "response_type is null or empty",
                    new Uri(validatedRequest.RedirectUri.Uri),
                    OAuthConstants.Errors.InvalidRequest,
                    string.Empty,
                    validatedRequest.State);
            }

            // check response type (only code and token are supported)
            if (!request.response_type.Equals(OAuthConstants.ResponseTypes.Token, StringComparison.Ordinal) &&
                !request.response_type.Equals(OAuthConstants.ResponseTypes.Code, StringComparison.Ordinal))
            {
                throw new AuthorizeRequestClientException(
                    "response_type is not token or code: " + request.response_type,
                    new Uri(validatedRequest.RedirectUri.Uri),
                    OAuthConstants.Errors.UnsupportedResponseType,
                    string.Empty,
                    validatedRequest.State);
            }

            validatedRequest.ResponseType = request.response_type;
            Tracing.Information("Response type: " + validatedRequest.ResponseType);

            if (request.response_type == OAuthConstants.ResponseTypes.Code)
            {
                ValidateCodeResponseType(validatedRequest, request);
            }
            else if (request.response_type == OAuthConstants.ResponseTypes.Token)
            {
                ValidateTokenResponseType(validatedRequest, request);
            }
            else
            {
                throw new AuthorizeRequestClientException(
                    "Invalid response_type: " + request.response_type,
                    new Uri(validatedRequest.RedirectUri.Uri),
                    OAuthConstants.Errors.UnsupportedResponseType,
                    request.response_type,
                    validatedRequest.State);
            }

            ValidateScopes(request, validatedRequest);

            // TODO: fix based upon past "remember me" settings
            validatedRequest.ShowConsent = client.RequireConsent || application.RequireConsent;

            Tracing.Information("Authorize request validation successful.");
            return validatedRequest;
        }
        private void ValidateRefreshTokenGrant(ValidatedRequest validatedRequest, TokenRequest request)
        {
            if (_handleManager == null)
            {
                throw new ArgumentNullException("HandleManager");
            }

            if (!validatedRequest.Client.AllowRefreshToken)
            {
                throw new TokenRequestValidationException(
                    "Refresh tokens not allowed for client",
                    OAuthConstants.Errors.UnauthorizedClient);
            }

            // check for refresh token
            if (string.IsNullOrWhiteSpace(request.Refresh_Token))
            {
                throw new TokenRequestValidationException(
                    "Missing refresh token",
                    OAuthConstants.Errors.InvalidGrant);
            }

            validatedRequest.RefreshToken = request.Refresh_Token;
            Tracing.Information("Refresh token: " + validatedRequest.RefreshToken);

            // check for refresh token in datastore
            var handle = _handleManager.Get(validatedRequest.RefreshToken);
            if (handle == null)
            {
                throw new TokenRequestValidationException(
                    "Refresh token not found: " + validatedRequest.RefreshToken,
                    OAuthConstants.Errors.InvalidGrant);
            }

            validatedRequest.StoredGrant = handle;
            Tracing.Information("Token handle found: " + handle.GrantId);

            // make sure the refresh token has an expiration time
            if (validatedRequest.StoredGrant.Expiration == null)
            {
                throw new TokenRequestValidationException(
                    "No expiration time set for refresh token. That's not allowed.",
                    OAuthConstants.Errors.InvalidGrant);
            }

            // make sure refresh token has not expired
            if (DateTime.UtcNow > validatedRequest.StoredGrant.Expiration)
            {
                throw new TokenRequestValidationException(
                    "Refresh token expired.",
                    OAuthConstants.Errors.InvalidGrant);
            }

            // check the client binding
            if (handle.Client.ClientId != validatedRequest.Client.ClientId)
            {
                throw new TokenRequestValidationException(
                    string.Format("Client {0} is trying to refresh token from {1}.", validatedRequest.Client.ClientId, handle.Client.ClientId),
                    OAuthConstants.Errors.InvalidGrant);
            }
        }
        private static void ValidateScopes(ValidatedRequest validatedRequest, TokenRequest request)
        {
            // validate scope
            if (string.IsNullOrWhiteSpace(request.Scope))
            {
                throw new TokenRequestValidationException(
                    "Missing scope",
                    OAuthConstants.Errors.InvalidScope);
            }

            // make sure client is allowed to request all scope
            var requestedScopes = request.Scope.Split(' ').ToList();
            List<Scope> resultingScopes;

            if (validatedRequest.Application.Scopes.TryValidateScopes(validatedRequest.Client.ClientId, requestedScopes, out resultingScopes))
            {
                validatedRequest.Scopes = resultingScopes;
                Tracing.InformationFormat("Requested scopes: {0}", request.Scope);
            }
            else
            {
                throw new TokenRequestValidationException(
                    "Invalid scope",
                    OAuthConstants.Errors.InvalidScope);
            }
        }
        private void ValidateAssertionGrant(ValidatedRequest validatedRequest, TokenRequest request)
        {
            ValidateScopes(validatedRequest, request);

            if (validatedRequest.Client.Flow != OAuthFlow.Assertion)
            {
                throw new TokenRequestValidationException(
                    "Assertion flow not allowed for client",
                    OAuthConstants.Errors.UnauthorizedClient);
            }
        }
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing resource owner credential request");

            ClaimsPrincipal principal;
            try
            {
                principal = _rocv.Validate(validatedRequest.UserName, validatedRequest.Password);
            }
            catch (Exception ex)
            {
                Tracing.Error("Resource owner credential validation failed: " + ex.ToString());
                throw;
            }

            if (principal != null && principal.Identity.IsAuthenticated)
            {
                var response = _tokenService.CreateTokenResponse(validatedRequest, principal);

                // check if refresh token is enabled for the client
                if (validatedRequest.Client.AllowRefreshToken && validatedRequest.Application.AllowRefreshToken)
                {
                    var handle = StoredGrant.CreateRefreshTokenHandle(
                        principal.GetSubject(),
                        validatedRequest.Client,
                        validatedRequest.Application,
                        principal.Claims,
                        validatedRequest.Scopes,
                        DateTime.UtcNow.AddYears(5));

                    _handleManager.Add(handle);
                    response.RefreshToken = handle.GrantId;
                }

                return Request.CreateTokenResponse(response);
            }
            else
            {
                return Request.CreateOAuthErrorResponse(OAuthConstants.Errors.InvalidGrant);
            }
        }
        private HttpResponseMessage ProcessRefreshTokenRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing refresh token request");

            var response = _tokenService.CreateTokenResponse(validatedRequest.StoredGrant, _handleManager);
            return Request.CreateTokenResponse(response);
        }
        private HttpResponseMessage ProcessAuthorizationCodeRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing authorization code request");

            var tokenService = new TokenService(_config.GlobalConfiguration);
            var response = tokenService.CreateTokenResponse(validatedRequest.TokenHandle, _handleManager);

            return Request.CreateTokenResponse(response);
        }
        public virtual TokenResponse CreateTokenResponseFromRefreshToken(StoredGrant handle, IStoredGrantManager handleManager)
        {
            var resourceOwner = Principal.Create(
                "OAuth2",
                handle.ResourceOwner.ToClaims().ToArray());

            if (DateTime.UtcNow > handle.Expiration)
            {
                throw new InvalidOperationException("Refresh token has expired.");
            }

            var validatedRequest = new ValidatedRequest
            {
                Client = handle.Client,
                Application = handle.Application,
                Scopes = handle.Scopes,
            };

            var response = CreateTokenResponse(validatedRequest, resourceOwner);

            if (handle.CreateRefreshToken)
            {
                StoredGrant refreshTokenHandle;

                if (validatedRequest.Application.AllowSlidingRefreshTokenExpiration)
                {
                    var rememberTimeSpan = handle.Expiration.Subtract(handle.Created);
                    var newRefreshTokenExpiration = DateTime.UtcNow.Add(rememberTimeSpan);

                    refreshTokenHandle = StoredGrant.CreateRefreshTokenHandle(
                        resourceOwner.GetSubject(),
                        handle.Client,
                        handle.Application,
                        resourceOwner.Claims,
                        handle.Scopes,
                        newRefreshTokenExpiration,
                        createRefreshToken: validatedRequest.Client.AllowRefreshToken && validatedRequest.Application.AllowRefreshToken);
                }
                else
                {
                    refreshTokenHandle = StoredGrant.CreateRefreshTokenHandle(
                        resourceOwner.GetSubject(),
                        handle.Client,
                        handle.Application,
                        resourceOwner.Claims,
                        handle.Scopes,
                        handle.Expiration,
                        createRefreshToken: validatedRequest.Client.AllowRefreshToken && validatedRequest.Application.AllowRefreshToken);
                }

                response.RefreshToken = refreshTokenHandle.GrantId;

                handleManager.Add(refreshTokenHandle);
                handleManager.Delete(handle.GrantId);
            }
            else
            {
                response.RefreshToken = handle.GrantId;
            }    
            return response;
        }
        private void ValidateClientCredentialsGrant(ValidatedRequest validatedRequest, TokenRequest request)
        {
            if (validatedRequest.Client.Flow != OAuthFlow.Client)
            {
                throw new TokenRequestValidationException(
                    "Client flow not allowed for client",
                    OAuthConstants.Errors.UnsupportedGrantType);
            }

            ValidateScopes(validatedRequest, request);
        }
        public ValidatedRequest Validate(Application application, TokenRequest request, ClaimsPrincipal clientPrincipal)
        {
            var validatedRequest = new ValidatedRequest();

            // validate request model binding
            if (request == null)
            {
                throw new TokenRequestValidationException(
                    "Invalid request parameters.",
                    OAuthConstants.Errors.InvalidRequest);
            }

            validatedRequest.Application = application;
            Tracing.InformationFormat("OAuth2 application: {0} ({1})",
                validatedRequest.Application.Name,
                validatedRequest.Application.Namespace);

            // grant type is required
            if (string.IsNullOrWhiteSpace(request.Grant_Type))
            {
                throw new TokenRequestValidationException(
                    "Missing grant_type",
                    OAuthConstants.Errors.UnsupportedGrantType);
            }

            validatedRequest.GrantType = request.Grant_Type;
            Tracing.Information("Grant type: " + validatedRequest.GrantType);

            // validate client credentials
            var client = ValidateClient(clientPrincipal, validatedRequest.Application);
            if (client == null)
            {
                throw new TokenRequestValidationException(
                    "Invalid client: " + ClaimsPrincipal.Current.Identity.Name,
                    OAuthConstants.Errors.InvalidClient);
            }

            validatedRequest.Client = client;
            Tracing.InformationFormat("Client: {0} ({1})",
                validatedRequest.Client.Name,
                validatedRequest.Client.ClientId);

            switch (request.Grant_Type)
            {
                case OAuthConstants.GrantTypes.AuthorizationCode:
                    ValidateCodeGrant(validatedRequest, request);
                    break;
                case OAuthConstants.GrantTypes.Password:
                    ValidatePasswordGrant(validatedRequest, request);
                    break;
                case OAuthConstants.GrantTypes.RefreshToken:
                    ValidateRefreshTokenGrant(validatedRequest, request);
                    break;
                case OAuthConstants.GrantTypes.ClientCredentials:
                    ValidateClientCredentialsGrant(validatedRequest, request);
                    break;
                default:
                    throw new TokenRequestValidationException(
                        "Invalid grant_type: " + request.Grant_Type,
                        OAuthConstants.Errors.UnsupportedGrantType);
            }

            Tracing.Information("Token request validation successful.");
            return validatedRequest;
        }
        private void ValidateCodeGrant(ValidatedRequest validatedRequest, TokenRequest request)
        {
            if (_handleManager == null)
            {
                throw new ArgumentNullException("HandleManager");
            }

            if (validatedRequest.Client.Flow != OAuthFlow.Code)
            {
                throw new TokenRequestValidationException(
                    "Code flow not allowed for client",
                    OAuthConstants.Errors.UnsupportedGrantType);
            }

            // code needs to be present
            if (string.IsNullOrWhiteSpace(request.Code))
            {
                throw new TokenRequestValidationException(
                    "Missing authorization code",
                    OAuthConstants.Errors.InvalidGrant);
            }

            validatedRequest.AuthorizationCode = request.Code;
            Tracing.Information("Authorization code: " + validatedRequest.AuthorizationCode);
            
            // check for authorization code in datastore
            var handle = _handleManager.Get(validatedRequest.AuthorizationCode);
            if (handle == null)
            {
                throw new TokenRequestValidationException(
                    "Authorization code not found: " + validatedRequest.AuthorizationCode,
                    OAuthConstants.Errors.InvalidGrant);
            }

            validatedRequest.TokenHandle = handle;
            Tracing.Information("Token handle found: " + handle.HandleId);

            // check the client binding
            if (handle.Client.ClientId != validatedRequest.Client.ClientId)
            {
                throw new TokenRequestValidationException(
                    string.Format("Client {0} is trying to request token using an authorization code from {1}.", validatedRequest.Client.ClientId, handle.Client.ClientId),
                    OAuthConstants.Errors.InvalidGrant);
            }

            // redirect URI is required
            if (string.IsNullOrWhiteSpace(request.Redirect_Uri))
            {
                throw new TokenRequestValidationException(
                    string.Format("Redirect URI is missing"),
                    OAuthConstants.Errors.InvalidRequest);
            }

            // check if redirect URI from authorize and token request match
            if (!handle.RedirectUri.Equals(request.Redirect_Uri))
            {
                throw new TokenRequestValidationException(
                    string.Format("Redirect URI in token request ({0}), does not match redirect URI from authorize request ({1})", validatedRequest.RedirectUri, handle.RedirectUri),
                    OAuthConstants.Errors.InvalidRequest);
            }
        }
        private ActionResult PerformImplicitGrant(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Performing implict grant");

            var sts = new TokenService(this._config.GlobalConfiguration);
            var response = sts.CreateTokenResponse(validatedRequest, ClaimsPrincipal.Current);

            var tokenString = string.Format("access_token={0}&token_type={1}&expires_in={2}",
                    response.AccessToken,
                    response.TokenType,
                    response.ExpiresIn);

            if (!string.IsNullOrWhiteSpace(validatedRequest.State))
            {
                tokenString = string.Format("{0}&state={1}", tokenString, Server.UrlEncode(validatedRequest.State));
            }

            var redirectString = string.Format("{0}#{1}",
                    validatedRequest.RedirectUri.Uri,
                    tokenString);

            Tracing.Information("Sending token response to redirect URI");
            return Redirect(redirectString);
        }
        protected virtual IEnumerable<Claim> CreateClaims(ValidatedRequest request, ClaimsPrincipal resourceOwner = null)
        {
            var claims = new List<Claim>();

            claims.AddRange(CreateRequestClaims(request));

            if (resourceOwner != null)
            {
                claims.AddRange(CreateResourceOwnerClaims(resourceOwner));
            }

            return claims;
        }
        private HttpResponseMessage ProcessClientCredentialsRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing refresh token request");

            var response = _tokenService.CreateTokenResponse(validatedRequest);
            return Request.CreateTokenResponse(response);
        }
        private void ValidateRefreshTokenGrant(ValidatedRequest validatedRequest, TokenRequest request)
        {
            if (_handleManager == null)
            {
                throw new ArgumentNullException("HandleManager");
            }

            if (!validatedRequest.Client.AllowRefreshToken)
            {
                throw new TokenRequestValidationException(
                    "Refresh tokens not allowed for client",
                    OAuthConstants.Errors.UnsupportedGrantType);
            }

            // check for refresh token
            if (string.IsNullOrWhiteSpace(request.Refresh_Token))
            {
                throw new TokenRequestValidationException(
                    "Missing refresh token",
                    OAuthConstants.Errors.InvalidGrant);
            }

            validatedRequest.RefreshToken = request.Refresh_Token;
            Tracing.Information("Refresh token: " + validatedRequest.RefreshToken);

            // check for refresh token in datastore
            var handle = _handleManager.Get(validatedRequest.RefreshToken);
            if (handle == null)
            {
                throw new TokenRequestValidationException(
                    "Refresh token not found: " + validatedRequest.RefreshToken,
                    OAuthConstants.Errors.InvalidGrant);
            }

            validatedRequest.TokenHandle = handle;
            Tracing.Information("Token handle found: " + handle.HandleId);

            // check the client binding
            if (handle.Client.ClientId != validatedRequest.Client.ClientId)
            {
                throw new TokenRequestValidationException(
                    string.Format("Client {0} is trying to refresh token from {1}.", validatedRequest.Client.ClientId, handle.Client.ClientId),
                    OAuthConstants.Errors.InvalidGrant);
            }
        }
        private HttpResponseMessage ProcessAuthorizationCodeRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing authorization code request");

            var response = _tokenService.CreateTokenResponse(validatedRequest.StoredGrant, _handleManager);
            return Request.CreateTokenResponse(response);
        }
        private void ValidatePasswordGrant(ValidatedRequest validatedRequest, TokenRequest request)
        {
            if (validatedRequest.Client.Flow != OAuthFlow.ResourceOwner)
            {
                throw new TokenRequestValidationException(
                    "Resource owner password flow not allowed for client",
                    OAuthConstants.Errors.UnsupportedGrantType);
            }

            ValidateScopes(validatedRequest, request);

            // extract username and password
            if (string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password))
            {
                throw new TokenRequestValidationException(
                    "Missing Username or password.",
                    OAuthConstants.Errors.InvalidGrant);
            }
            else
            {
                validatedRequest.UserName = request.UserName;
                validatedRequest.Password = request.Password;

                Tracing.Information("Resource owner: " + request.UserName);
            }
        }
        protected virtual JwtSecurityToken CreateToken(ValidatedRequest request, IEnumerable<Claim> claims)
        {
            var token = new JwtSecurityToken(
                issuer: globalConfiguration.Issuer,
                audience: request.Application.Audience,
                claims: claims,
                lifetime: new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(request.Application.TokenLifetime)),
                signingCredentials: request.Application.SigningCredentials);

            return token;
        }
 private void ValidateTokenResponseType(ValidatedRequest validatedRequest, AuthorizeRequest request)
 {
     if (validatedRequest.Client.Flow != OAuthFlow.Implicit)
     {
         throw new AuthorizeRequestClientException(
             "response_type is not allowed: " + request.response_type,
             new Uri(validatedRequest.RedirectUri.Uri),
             OAuthConstants.Errors.UnsupportedResponseType,
             request.response_type,
             validatedRequest.State);
     }
 }
        protected virtual List<Claim> CreateRequestClaims(ValidatedRequest request)
        {
            var claims = new List<Claim>
            {
                new Claim("client_id", request.Client.ClientId)
            };

            request.Scopes.ForEach(s => claims.Add(new Claim("scope", s.Name)));

            return claims;
        }
        private void ValidateCodeResponseType(ValidatedRequest validatedRequest, AuthorizeRequest request)
        {
            // make sure response type allowed for this client
            if (validatedRequest.Client.Flow != OAuthFlow.Code)
            {
                throw new AuthorizeRequestClientException(
                   "response_type is not allowed: " + request.response_type,
                   new Uri(validatedRequest.RedirectUri.Uri),
                   OAuthConstants.Errors.UnsupportedResponseType,
                   request.response_type,
                   validatedRequest.State);
            }

            if (validatedRequest.Client.AllowRefreshToken && validatedRequest.Application.AllowRefreshToken)
            {
                Tracing.Information("The request allows arefresh token.");
                validatedRequest.RequestingRefreshToken = true;
            }

            if (validatedRequest.Client.RequireConsent || validatedRequest.Application.RequireConsent)
            {
                Tracing.Information("Consent is required.");
                validatedRequest.ShowConsent = true;
            }
        }
        public virtual TokenResponse CreateTokenResponseFromRefreshToken(TokenHandle handle, ITokenHandleManager handleManager)
        {
            var resourceOwner = Principal.Create(
                "OAuth2",
                handle.ResourceOwner.ToClaims().ToArray());

            if (DateTime.UtcNow > handle.Expiration)
            {
                throw new InvalidOperationException("Refresh token has expired.");
            }

            var validatedRequest = new ValidatedRequest
            {
                Client = handle.Client,
                Application = handle.Application,
                Scopes = handle.Scopes,
            };

            var response = CreateTokenResponse(validatedRequest, resourceOwner);
            response.RefreshToken = handle.HandleId;
            
            return response;
        }
        private static void ValidateScopes(AuthorizeRequest request, ValidatedRequest validatedRequest)
        {
            // validate scopes
            if (string.IsNullOrEmpty(request.scope))
            {
                throw new AuthorizeRequestClientException(
                    "Missing scope.",
                    new Uri(validatedRequest.RedirectUri.Uri),
                    OAuthConstants.Errors.InvalidScope,
                    validatedRequest.ResponseType,
                    validatedRequest.State);
            }

            var requestedScopes = request.scope.Split(' ').ToList();
            List<Scope> resultingScopes;

            if (validatedRequest.Application.Scopes.TryValidateScopes(validatedRequest.Client.ClientId, requestedScopes, out resultingScopes))
            {
                validatedRequest.Scopes = resultingScopes;
                Tracing.InformationFormat("Requested scopes: {0}", request.scope);
            }
            else
            {
                throw new AuthorizeRequestClientException(
                    "Invalid scope.",
                    new Uri(validatedRequest.RedirectUri.Uri),
                    OAuthConstants.Errors.InvalidScope,
                    validatedRequest.ResponseType,
                    validatedRequest.State);
            }
        }