示例#1
0
        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));
        }
        private HttpResponseMessage ProcessAuthorizationCodeRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing authorization code request");

            var tokenService = new OidcTokenService(
                ServerConfiguration.Global.IssuerUri,
                ServerConfiguration.Keys.SigningCertificate);

            var response = tokenService.CreateTokenResponse(validatedRequest.Grant,
                                                            validatedRequest.Client.AccessTokenLifetime);

            Grants.Delete(validatedRequest.Grant.GrantId);

            if (validatedRequest.Grant.Scopes.Contains(OidcConstants.Scopes.OfflineAccess) &&
                validatedRequest.Client.AllowRefreshToken)
            {
                var refreshToken = StoredGrant.CreateRefreshToken(
                    validatedRequest.Grant.ClientId,
                    validatedRequest.Grant.Subject,
                    validatedRequest.Grant.Scopes,
                    validatedRequest.Client.RefreshTokenLifetime);

                Grants.Add(refreshToken);
                response.RefreshToken = refreshToken.GrantId;
            }

            return(Request.CreateTokenResponse(response));
        }
        public virtual TokenResponse CreateTokenResponseFromAuthorizationCode(StoredGrant handle, IStoredGrantManager 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 = StoredGrant.CreateRefreshTokenHandle(
                    resourceOwner.GetSubject(),
                    handle.Client,
                    handle.Application,
                    resourceOwner.Claims,
                    handle.Scopes,
                    handle.RefreshTokenExpiration.Value);

                handleManager.Add(refreshTokenHandle);
                response.RefreshToken = refreshTokenHandle.GrantId;
            }

            handleManager.Delete(handle.GrantId);

            return(response);
        }
        protected virtual ActionResult PerformAuthorizationCodeGrant(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing authorization code request");

            var grant = StoredGrant.CreateAuthorizationCode(
                validatedRequest.Client.ClientId,
                ClaimsPrincipal.Current.Identity.Name,
                validatedRequest.Scopes,
                validatedRequest.RedirectUri,
                60);

            Grants.Add(grant);

            var tokenString = string.Format("code={0}", grant.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,
                                               tokenString);

            return(Redirect(redirectString));
        }
        public Models.StoredGrant Get(string handleIdentifier)
        {
            DateTime expiration;

            if (_expired)
            {
                expiration = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1));
            }
            else
            {
                expiration = DateTime.UtcNow.Add(TimeSpan.FromHours(1));
            }

            if (handleIdentifier == _id)
            {
                var handle = new StoredGrant
                {
                    Client = new Client
                    {
                        ClientId = _clientId
                    },

                    RedirectUri = _redirectUri,
                    Expiration  = expiration
                };

                return(handle);
            }

            return(null);
        }
        public virtual TokenResponse CreateTokenResponse(StoredGrant handle, IStoredGrantManager handleManager)
        {
            if (handle.Type == StoredGrantType.AuthorizationCode)
            {
                return(CreateTokenResponseFromAuthorizationCode(handle, handleManager));
            }
            if (handle.Type == StoredGrantType.RefreshTokenIdentifier)
            {
                return(CreateTokenResponseFromRefreshToken(handle, handleManager));
            }

            throw new ArgumentException("handle.Type");
        }
示例#7
0
        public OidcTokenResponse CreateTokenResponse(StoredGrant grant, int accessTokenLifetime)
        {
            var accessToken = CreateAccessToken(grant.Subject, _issuer + "/userinfo", grant.ClientId, grant.Scopes, accessTokenLifetime);
            var response    = new OidcTokenResponse
            {
                AccessToken = accessToken.ToJwtString(),
                TokenType   = "Bearer",
                ExpiresIn   = accessTokenLifetime * 60
            };

            if (grant.GrantType == StoredGrantType.AuthorizationCode)
            {
                var idToken = CreateIdentityToken(grant.Subject, grant.ClientId, 60);
                response.IdentityToken = idToken.ToJwtString();
            }

            return(response);
        }
        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 sts      = new TokenService(this._config.GlobalConfiguration);
                var response = sts.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));
            }
        }
        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);

            response.RefreshToken = handle.GrantId;

            return(response);
        }
示例#10
0
        public ActionResult HandleConsentResponse(string appName, string button, string[] scopes, AuthorizeRequest request, int?rememberDuration = null)
        {
            Tracing.Start("OAuth2 Authorize Endoint - Consent response");

            // make sure application is registered
            var application = _config.FindApplication(appName);

            if (application == null)
            {
                Tracing.Error("Application not found: " + appName);
                return(HttpNotFound());
            }

            if (button == "no")
            {
                Tracing.Information("User denies access token request.");
                return(new ClientErrorResult(new Uri(request.redirect_uri), OAuthConstants.Errors.AccessDenied, request.response_type, request.state));
            }

            if (button == "yes")
            {
                Tracing.Information("User allows access token request.");

                ValidatedRequest validatedRequest;
                try
                {
                    validatedRequest = new AuthorizeRequestValidator().Validate(application, request);
                }
                catch (AuthorizeRequestValidationException ex)
                {
                    Tracing.Error("Aborting OAuth2 authorization request");
                    return(this.AuthorizeValidationError(ex));
                }

                if (scopes == null || scopes.Length == 0)
                {
                    ModelState.AddModelError("", "Please choose at least one permission.");
                    return(View("Consent", validatedRequest));
                }

                // parse scopes form post and substitue scopes
                validatedRequest.Scopes.RemoveAll(x => !scopes.Contains(x.Name));

                // store consent decision if
                //  checkbox was checked
                //  and storage is allowed
                //  and flow == implicit
                if (validatedRequest.Application.AllowRememberConsentDecision &&
                    validatedRequest.ResponseType == OAuthConstants.ResponseTypes.Token &&
                    rememberDuration == -1)
                {
                    var handle = StoredGrant.CreateConsentDecision(
                        ClaimsPrincipal.Current.GetSubject(),
                        validatedRequest.Client,
                        validatedRequest.Application,
                        validatedRequest.Scopes);

                    _handleManager.Add(handle);

                    Tracing.Information("Consent decision stored.");
                }

                // parse refresh token lifetime if
                // code flow is used
                // and refresh tokens are allowed
                if (validatedRequest.RequestingRefreshToken &&
                    rememberDuration != null &&
                    validatedRequest.Client.Flow == OAuthFlow.Code)
                {
                    if (rememberDuration == -1)
                    {
                        validatedRequest.RequestedRefreshTokenExpiration = DateTime.UtcNow.AddYears(50);
                    }
                    else
                    {
                        validatedRequest.RequestedRefreshTokenExpiration = DateTime.UtcNow.AddHours(rememberDuration.Value);
                    }

                    Tracing.Information("Selected refresh token lifetime in hours: " + rememberDuration);
                }

                var grantResult = PerformGrant(validatedRequest);
                if (grantResult != null)
                {
                    return(grantResult);
                }
            }

            return(new ClientErrorResult(
                       new Uri(request.redirect_uri),
                       OAuthConstants.Errors.InvalidRequest,
                       request.response_type,
                       request.state));
        }
        public void Init()
        {
            DataProtectection.Instance = new NoProtection();
            globalConfiguration        = new GlobalConfiguration()
            {
                Issuer = "Test Issuer"
            };

            rocv                    = new Mock <IResourceOwnerCredentialValidation>();
            config                  = new Mock <IAuthorizationServerConfiguration>();
            handleManager           = new Mock <IStoredGrantManager>();
            assertionGrantValidator = new Mock <IAssertionGrantValidation>();
            clientManager           = new Mock <IClientManager>();

            tokenService = new TokenService(globalConfiguration);


            #region Setup Test Client
            string secret              = "12345678";
            byte[] encodedByte         = System.Text.ASCIIEncoding.ASCII.GetBytes(secret);
            string base64EncodedSecret = Convert.ToBase64String(encodedByte);
            _Client = new Client()
            {
                ClientId          = "MobileAppShop",
                ClientSecret      = base64EncodedSecret,
                Flow              = OAuthFlow.ResourceOwner,
                AllowRefreshToken = true
            };
            #endregion

            #region Setup Test Application
            var scope = new Scope();
            scope.Name           = "read";
            scope.AllowedClients = new List <Client>();
            scope.AllowedClients.Add(_Client);
            _Scopes = new List <Scope>();
            _Scopes.Add(scope);

            string      symmetricKey = "C33333333333333333333333335=";
            byte[]      keybytes     = Convert.FromBase64String(symmetricKey);
            SecurityKey securityKey  = new InMemorySymmetricSecurityKey(keybytes);
            _Application = new Application()
            {
                Name              = "Test Application 1",
                Scopes            = _Scopes,
                Audience          = "Test Audience",
                TokenLifetime     = 1,
                AllowRefreshToken = true,
            };
            #endregion

            #region Setup Example StoredGrant
            Claim[] resourceOwnerClaims = { new Claim("Username", "JohnSmith"), new Claim("sub", "JohnSmith") };
            _StoredGrant = new StoredGrant()
            {
                GrantId                = "MyFavouriteRefrehToken1234",
                CreateRefreshToken     = true,
                Client                 = _Client,
                ResourceOwner          = resourceOwnerClaims.ToStoredGrantClaims().ToList(),
                Expiration             = DateTime.Now.AddDays(1),
                RefreshTokenExpiration = DateTime.Now.AddMonths(1),
                Type        = StoredGrantType.RefreshTokenIdentifier,
                Scopes      = _Scopes,
                Application = _Application
            };
            #endregion

            #region Setup Mocking Objects
            // IAuthorizationServerConfiguration
            config.Setup(x => x.FindApplication(It.IsNotNull <string>()))
            .Returns((string name) =>
            {
                return(_Application);
            });
            config.Setup(x => x.GlobalConfiguration).Returns(() => globalConfiguration);

            // IClientManager
            clientManager.Setup(x => x.Get(It.IsNotNull <string>()))
            .Returns((string clientId) =>
            {
                return(_Client);
            });

            // IResourceOwnerCredentialValidation
            rocv.Setup(x => x.Validate(It.IsNotNull <string>(), It.IsNotNull <string>()))
            .Returns((string username, string password) =>
            {
                return(Principal.Create("Test", resourceOwnerClaims));
            });

            // IStoredGrantManager
            handleManager.Setup(x => x.Get(It.IsNotNull <string>()))
            .Returns((string grantIdentifier) =>
            {
                return(_StoredGrant);
            });

            #endregion

            _TokenController = new TokenController(
                rocv.Object,
                config.Object,
                handleManager.Object,
                assertionGrantValidator.Object,
                tokenService,
                clientManager.Object);
            _TokenController.Request = new HttpRequestMessage();
            _TokenController.Request.SetConfiguration(new HttpConfiguration());
        }
        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);
        }