public Task<ValidationResult> ValidateAuthorizeRequestAsync(ValidatedAuthorizeRequest request)
 {
     return Task.FromResult(new ValidationResult
     {
         IsError = false
     });
 }
        public async Task<AuthorizeResponse> CreateCodeFlowResponseAsync(ValidatedAuthorizeRequest request, ClaimsPrincipal subject)
        {
            var code = new AuthorizationCode
            {
                Client = request.Client,
                Subject = subject,

                IsOpenId = request.IsOpenIdRequest,
                RequestedScopes = request.ValidatedScopes.GrantedScopes,
                RedirectUri = request.RedirectUri,

                WasConsentShown = request.WasConsentShown,
                RefreshTokenLifetime = request.Client.RefreshTokenLifetime
            };

            // store id token and access token and return authorization code
            var id = Guid.NewGuid().ToString("N");
            await _authorizationCodes.StoreAsync(id, code);

            return new AuthorizeResponse
            {
                RedirectUri = request.RedirectUri,
                Code = id,
                State = request.State
            };
        }
        public async Task<AuthorizeResponse> CreateImplicitFlowResponseAsync(ValidatedAuthorizeRequest request)
        {
            string accessTokenValue = null;
            int accessTokenLifetime = 0;

            if (request.IsResourceRequest)
            {
                var accessToken = await _tokenService.CreateAccessTokenAsync(request.Subject, request.Client, request.ValidatedScopes.GrantedScopes, request.Raw);
                accessTokenLifetime = accessToken.Lifetime;

                accessTokenValue = await _tokenService.CreateSecurityTokenAsync(accessToken);
            }

            string jwt = null;
            if (request.IsOpenIdRequest)
            {
                var idToken = await _tokenService.CreateIdentityTokenAsync(request.Subject, request.Client, request.ValidatedScopes.GrantedScopes, !request.AccessTokenRequested, request.Raw, accessTokenValue);
                jwt = await _tokenService.CreateSecurityTokenAsync(idToken);
            }

            return new AuthorizeResponse
            {
                RedirectUri = request.RedirectUri,
                AccessToken = accessTokenValue,
                AccessTokenLifetime = accessTokenLifetime,
                IdentityToken = jwt,
                State = request.State,
                Scope = request.ValidatedScopes.GrantedScopes.ToSpaceSeparatedString()
            };
        }
        public AuthorizeRequestValidator(ICoreSettings core, ILogger logger, IUserService users, ICustomRequestValidator customValidator)
        {
            _core = core;
            _logger = logger;
            _users = users;
            _customValidator = customValidator;

            _validatedRequest = new ValidatedAuthorizeRequest();
            _validatedRequest.CoreSettings = _core;
        }
        public AuthorizeRequestValidator(IdentityServerOptions options, IScopeStore scopes, IClientStore clients, ICustomRequestValidator customValidator)
        {
            _options = options;
            _scopes = scopes;
            _clients = clients;
            _customValidator = customValidator;

            _validatedRequest = new ValidatedAuthorizeRequest();
            _validatedRequest.IdentityServerOptions = _options;
        }
        public AuthorizeRequestValidator(CoreSettings core, IScopeService scopes, IClientService clients, IUserService users, ICustomRequestValidator customValidator)
        {
            _core = core;
            _scopes = scopes;
            _clients = clients;
            _users = users;
            _customValidator = customValidator;

            _validatedRequest = new ValidatedAuthorizeRequest();
            _validatedRequest.CoreSettings = _core;
        }
 public void ProcessConsentAsync_AllowsNullConsent()
 {
     var request = new ValidatedAuthorizeRequest()
     {
         ResponseMode = Constants.ResponseModes.Fragment,
         State = "12345",
         RedirectUri = new Uri("https://client.com/callback"),
         PromptMode = Constants.PromptModes.Consent
     }; 
     var result = subject.ProcessConsentAsync(request, null).Result;
 }
        private async Task<IHttpActionResult> CreateImplicitFlowAuthorizeResponseAsync(ValidatedAuthorizeRequest request)
        {
            var response = await _responseGenerator.CreateImplicitFlowResponseAsync(request);

            // create form post response if responseMode is set form_post
            if (request.ResponseMode == Constants.ResponseModes.FormPost)
            {
                return this.AuthorizeImplicitFormPostResponse(response);
            }

            return this.AuthorizeImplicitFragmentResponse(response);
        }
 private async Task<IHttpActionResult> CreateCodeFlowAuthorizeResponseAsync(ValidatedAuthorizeRequest request)
 {
     var response = await _responseGenerator.CreateCodeFlowResponseAsync(request, User as ClaimsPrincipal);
     return this.AuthorizeCodeResponse(response);
 }
        private async Task<IHttpActionResult> CreateAuthorizeResponseAsync(ValidatedAuthorizeRequest request)
        {
            if (request.Flow == Flows.Implicit)
            {
                return await CreateImplicitFlowAuthorizeResponseAsync(request);
            }

            if (request.Flow == Flows.Code)
            {
                return await CreateCodeFlowAuthorizeResponseAsync(request);
            }

            Logger.Error("Unsupported flow. Aborting.");
            throw new InvalidOperationException("Unsupported flow");
        }
 private IHttpActionResult CreateConsentResult(
     ValidatedAuthorizeRequest validatedRequest,
     UserConsent consent,
     NameValueCollection requestParameters,
     string errorMessage)
 {
     var env = Request.GetOwinEnvironment();
     var consentModel = new ConsentViewModel()
     {
         SiteName = _options.SiteName,
         SiteUrl = env.GetIdentityServerBaseUrl(),
         ErrorMessage = errorMessage,
         CurrentUser = User.GetName(),
         ClientName = validatedRequest.Client.ClientName,
         ClientUrl = validatedRequest.Client.ClientUri,
         ClientLogoUrl = validatedRequest.Client.LogoUri.AbsoluteUri,
         IdentityScopes = validatedRequest.GetIdentityScopes(),
         ApplicationScopes = validatedRequest.GetApplicationScopes(),
         AllowRememberConsent = validatedRequest.Client.AllowRememberConsent,
         RememberConsent = consent != null ? consent.RememberConsent : true,
         LoginWithDifferentAccountUrl = Url.Route(Constants.RouteNames.Oidc.SwitchUser, null) + "?" + requestParameters.ToQueryString(),
         LogoutUrl = Url.Route(Constants.RouteNames.Oidc.EndSession, null),
         ConsentUrl = Url.Route(Constants.RouteNames.Oidc.Consent, null) + "?" + requestParameters.ToQueryString()
     };
     return new ConsentActionResult(_viewService, env, consentModel);
 }
Beispiel #12
0
        public LoginInteractionResponse ProcessLogin(ValidatedAuthorizeRequest request, ClaimsPrincipal user)
        {
            // pass through display mode to signin service
            if (request.DisplayMode.IsPresent())
            {
                _signIn.DisplayMode = request.DisplayMode;
            }

            // pass through ui locales to signin service
            if (request.UiLocales.IsPresent())
            {
                _signIn.UiLocales = request.UiLocales;
            }

            // check login_hint - we only support idp: right now
            if (request.LoginHint.IsPresent())
            {
                if (request.LoginHint.StartsWith("idp:"))
                {
                    _signIn.IdP = request.LoginHint.Substring(4);
                }
            }

            if (request.PromptMode == Constants.PromptModes.Login)
            {
                // remove prompt so when we redirect back in from login page
                // we won't think we need to force a prompt again
                request.Raw.Remove(Constants.AuthorizeRequest.Prompt);
                return(new LoginInteractionResponse
                {
                    SignInMessage = _signIn
                });
            }

            // unauthenticated user
            if (!user.Identity.IsAuthenticated)
            {
                // prompt=none means user must be signed in already
                if (request.PromptMode == Constants.PromptModes.None)
                {
                    return(new LoginInteractionResponse
                    {
                        Error = new AuthorizeError
                        {
                            ErrorType = ErrorTypes.Client,
                            Error = Constants.AuthorizeErrors.LoginRequired,
                            ResponseMode = request.ResponseMode,
                            ErrorUri = request.RedirectUri,
                            State = request.State
                        }
                    });
                }

                return(new LoginInteractionResponse
                {
                    SignInMessage = _signIn
                });
            }

            // check authentication freshness
            if (request.MaxAge.HasValue)
            {
                var authTime = user.GetAuthenticationTime();
                if (DateTime.UtcNow > authTime.AddSeconds(request.MaxAge.Value))
                {
                    return(new LoginInteractionResponse
                    {
                        SignInMessage = _signIn
                    });
                }
            }

            return(new LoginInteractionResponse());
        }
 public void ProcessConsentAsync_NoPromptMode_ConsentServiceRequiresConsent_ConsentNotGranted_ReturnsErrorResult()
 {
     RequiresConsent(true);
     var request = new ValidatedAuthorizeRequest()
     {
         ResponseMode = Constants.ResponseModes.Fragment,
         State = "12345",
         RedirectUri = new Uri("https://client.com/callback"),
     };
     var consent = new UserConsent
     {
         Button = "no",
         RememberConsent = false,
         Scopes = new string[] { "read", "write" }
     };
     var result = subject.ProcessConsentAsync(request, consent).Result;
     Assert.IsTrue(request.WasConsentShown);
     Assert.IsTrue(result.IsError);
     Assert.AreEqual(ErrorTypes.Client, result.Error.ErrorType);
     Assert.AreEqual(Constants.AuthorizeErrors.AccessDenied, result.Error.Error);
     AssertErrorReturnsRequestValues(result.Error, request);
     AssertUpdateConsentNotCalled();
 }
Beispiel #14
0
        public async Task <ConsentInteractionResponse> ProcessConsentAsync(ValidatedAuthorizeRequest request, UserConsent consent = null)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.PromptMode != null &&
                request.PromptMode != Constants.PromptModes.None &&
                request.PromptMode != Constants.PromptModes.Consent)
            {
                throw new ArgumentException("Invalid PromptMode");
            }

            var consentRequired = await _consent.RequiresConsentAsync(request.Client, request.Subject, request.RequestedScopes);

            if (consentRequired && request.PromptMode == Constants.PromptModes.None)
            {
                return(new ConsentInteractionResponse
                {
                    Error = new AuthorizeError
                    {
                        ErrorType = ErrorTypes.Client,
                        Error = Constants.AuthorizeErrors.InteractionRequired,
                        ResponseMode = request.ResponseMode,
                        ErrorUri = request.RedirectUri,
                        State = request.State
                    }
                });
            }

            if (request.PromptMode == Constants.PromptModes.Consent || consentRequired)
            {
                var response = new ConsentInteractionResponse();

                // did user provide consent
                if (consent == null)
                {
                    // user was not yet shown conset screen
                    response.IsConsent = true;
                }
                else
                {
                    request.WasConsentShown = true;

                    // user was shown consent -- did they say yes or no
                    if (consent.WasConsentGranted == false)
                    {
                        // no need to show consent screen again
                        // build access denied error to return to client
                        response.Error = new AuthorizeError {
                            ErrorType    = ErrorTypes.Client,
                            Error        = Constants.AuthorizeErrors.AccessDenied,
                            ResponseMode = request.ResponseMode,
                            ErrorUri     = request.RedirectUri,
                            State        = request.State
                        };
                    }
                    else
                    {
                        // they said yes, set scopes they chose
                        request.ValidatedScopes.SetConsentedScopes(consent.ScopedConsented);

                        if (!request.ValidatedScopes.GrantedScopes.Any())
                        {
                            // they said yes, but didn't pick any scopes
                            // show consent again and provide error message
                            response.IsConsent    = true;
                            response.ConsentError = Messages.MustSelectAtLeastOnePermission;
                        }
                        else if (request.Client.AllowRememberConsent)
                        {
                            // remember consent
                            var scopes = Enumerable.Empty <string>();
                            if (consent.RememberConsent)
                            {
                                // remember what user actually selected
                                scopes = request.ValidatedScopes.GrantedScopes.Select(x => x.Name);
                            }

                            await _consent.UpdateConsentAsync(request.Client, request.Subject, scopes);
                        }
                    }
                }

                return(response);
            }

            return(new ConsentInteractionResponse());
        }
        public async Task<InteractionResponse> ProcessConsentAsync(ValidatedAuthorizeRequest request, UserConsent consent)
        {
            if (request.PromptMode == Constants.PromptModes.Consent ||
                await _consent.RequiresConsentAsync(request.Client, request.Subject, request.RequestedScopes))
            {
                var response = new InteractionResponse();

                // did user provide consent
                if (consent == null)
                {
                    // user was not yet shown conset screen
                    response.IsConsent = true;
                }
                else
                {
                    request.WasConsentShown = true;

                    // user was shown consent -- did they say yes or no
                    if (consent.WasConsentGranted == false)
                    {
                        // no need to show consent screen again
                        // build access denied error to return to client
                        response.IsError = true;
                        response.Error = new AuthorizeError { 
                            ErrorType = ErrorTypes.Client,
                            Error = Constants.AuthorizeErrors.AccessDenied,
                            ResponseMode = request.ResponseMode,
                            ErrorUri = request.RedirectUri, 
                            State = request.State
                        };
                    }
                    else
                    {
                        // they said yes, set scopes they chose
                        request.ValidatedScopes.SetConsentedScopes(consent.ScopedConsented);

                        if (!request.ValidatedScopes.GrantedScopes.Any())
                        {
                            // they said yes, but didn't pick any scopes
                            // show consent again and provide error message
                            response.IsConsent = true;
                            response.ConsentError = "Must select at least one permission.";
                        }
                        
                        if (request.Client.AllowRememberConsent)
                        {
                            // remember consent
                            var scopes = Enumerable.Empty<string>();
                            if (consent.RememberConsent)
                            {
                                // remember what user actually selected
                                scopes = request.ValidatedScopes.GrantedScopes.Select(x => x.Name);
                            }
                            
                            await _consent.UpdateConsentAsync(request.Client, request.Subject, scopes);
                        }
                    }
                }
                
                return response;
            }

            return new InteractionResponse();
        }
 private void AssertErrorReturnsRequestValues(AuthorizeError error, ValidatedAuthorizeRequest request)
 {
     Assert.AreEqual(request.ResponseMode, error.ResponseMode);
     Assert.AreEqual(request.RedirectUri, error.ErrorUri);
     Assert.AreEqual(request.State, error.State);
 }
 public void ProcessConsentAsync_AllowConsentSelected_SavesConsent()
 {
     RequiresConsent(true);
     var client = new Client { AllowRememberConsent = true };
     var user = new ClaimsPrincipal();
     var request = new ValidatedAuthorizeRequest()
     {
         ResponseMode = Constants.ResponseModes.Fragment,
         State = "12345",
         RedirectUri = new Uri("https://client.com/callback"),
         ValidatedScopes = new ScopeValidator(),
         Client = client,
         Subject = user
     };
     request.ValidatedScopes.AreScopesValid(new string[] { "read", "write" }, TestScopes.Get());
     var consent = new UserConsent
     {
         Button = "yes",
         RememberConsent = true,
         Scopes = new string[] { "read" }
     };
     var result = subject.ProcessConsentAsync(request, consent).Result;
     AssertUpdateConsentCalled(client, user, "read");
 }
 public void ProcessConsentAsync_PromptModeConsent_ConsentGranted_ScopesSelected_ReturnsConsentResult()
 {
     RequiresConsent(true);
     var request = new ValidatedAuthorizeRequest()
     {
         ResponseMode = Constants.ResponseModes.Fragment,
         State = "12345",
         RedirectUri = new Uri("https://client.com/callback"),
         ValidatedScopes = new ScopeValidator(),
         Client = new Client { }
     };
     request.ValidatedScopes.AreScopesValid(new string[] { "read", "write" }, TestScopes.Get());
     var consent = new UserConsent
     {
         Button = "yes",
         RememberConsent = false,
         Scopes = new string[] { "read" }
     };
     var result = subject.ProcessConsentAsync(request, consent).Result;
     Assert.AreEqual(1, request.ValidatedScopes.GrantedScopes.Count);
     Assert.AreEqual(request.ValidatedScopes.GrantedScopes.First().Name, "read");
     Assert.IsTrue(request.WasConsentShown);
     Assert.IsFalse(result.IsConsent);
     AssertUpdateConsentNotCalled();
 }
 public void ProcessConsentAsync_NoPromptMode_ConsentServiceRequiresConsent_ConsentGranted_NoScopesSelected_ReturnsConsentResult()
 {
     RequiresConsent(true);
     var request = new ValidatedAuthorizeRequest()
     {
         ResponseMode = Constants.ResponseModes.Fragment,
         State = "12345",
         RedirectUri = new Uri("https://client.com/callback"),
         ValidatedScopes = new ScopeValidator(),
         Client = new Client { }
     };
     var consent = new UserConsent
     {
         Button = "yes",
         RememberConsent = false,
         Scopes = new string[] {  }
     };
     var result = subject.ProcessConsentAsync(request, consent).Result;
     Assert.IsTrue(request.WasConsentShown);
     Assert.IsTrue(result.IsConsent);
     Assert.AreEqual(Messages.MustSelectAtLeastOnePermission, result.ConsentError);
     AssertUpdateConsentNotCalled();
 }
 private IHttpActionResult CreateConsentResult(
     ValidatedAuthorizeRequest validatedRequest, 
     NameValueCollection requestParameters, 
     string errorMessage)
 {
     var consentModel = new ConsentModel(validatedRequest, requestParameters);
     string name = User.GetName();
     
     return new EmbeddedHtmlResult(
         Request, 
         new LayoutModel
         {
             Server = _settings.SiteName,
             ErrorMessage = errorMessage,
             Page = "consent",
             Username = name,
             SwitchUrl = Url.Route("switch", null) + "?" + requestParameters.ToQueryString(),
             PageModel = consentModel
         });
 }
 public void ProcessConsentAsync_RequiresConsentButPromptModeIsNone_ReturnsErrorResult()
 {
     RequiresConsent(true);
     var request = new ValidatedAuthorizeRequest()
     {
         ResponseMode = Constants.ResponseModes.Fragment,
         State = "12345",
         RedirectUri = new Uri("https://client.com/callback"),
         PromptMode = Constants.PromptModes.None
     };
     var result = subject.ProcessConsentAsync(request).Result;
     Assert.IsFalse(request.WasConsentShown);
     Assert.IsTrue(result.IsError);
     Assert.AreEqual(ErrorTypes.Client, result.Error.ErrorType);
     Assert.AreEqual(Constants.AuthorizeErrors.InteractionRequired, result.Error.Error);
     AssertErrorReturnsRequestValues(result.Error, request);
     AssertUpdateConsentNotCalled();
 }
 public void ProcessConsentAsync_NoPromptMode_ConsentServiceRequiresConsent_NoPriorConsent_ReturnsConsentResult()
 {
     RequiresConsent(true);
     var request = new ValidatedAuthorizeRequest()
     {
         ResponseMode = Constants.ResponseModes.Fragment,
         State = "12345",
         RedirectUri = new Uri("https://client.com/callback"),
         PromptMode = Constants.PromptModes.Consent
     };
     var result = subject.ProcessConsentAsync(request).Result;
     Assert.IsFalse(request.WasConsentShown);
     Assert.IsTrue(result.IsConsent);
     AssertUpdateConsentNotCalled();
 }
        public InteractionResponse ProcessLogin(ValidatedAuthorizeRequest request, ClaimsPrincipal user)
        {
            // pass through display mode to signin service
            if (request.DisplayMode.IsPresent())
            {
                _signIn.DisplayMode = request.DisplayMode;
            }

            // pass through ui locales to signin service
            if (request.UiLocales.IsPresent())
            {
                _signIn.UILocales = request.UiLocales;
            }

            if (request.PromptMode == Constants.PromptModes.Login)
            {
                // remove prompt so when we redirect back in from login page
                // we won't think we need to force a prompt again
                request.Raw.Remove(Constants.AuthorizeRequest.Prompt);
                return new InteractionResponse
                {
                    IsLogin = true,
                    SignInMessage = _signIn
                };
            }

            // unauthenticated user
            if (!user.Identity.IsAuthenticated)
            {
                // prompt=none means user must be signed in already
                if (request.PromptMode == Constants.PromptModes.None)
                {
                    return new InteractionResponse
                    {
                        IsError = true,
                        Error = new AuthorizeError
                        {
                            ErrorType = ErrorTypes.Client,
                            Error = Constants.AuthorizeErrors.InteractionRequired,
                            ResponseMode = request.ResponseMode,
                            ErrorUri = request.RedirectUri,
                            State = request.State
                        }
                    };
                }

                return new InteractionResponse
                {
                    IsLogin = true,
                    SignInMessage = _signIn
                };
            }

            // check authentication freshness
            if (request.MaxAge.HasValue)
            {
                var authTime = user.GetAuthenticationTime();
                if (DateTime.UtcNow > authTime.AddSeconds(request.MaxAge.Value))
                {
                    return new InteractionResponse
                    {
                        IsLogin = true,
                        SignInMessage = _signIn
                    };
                }
            }
    
            return new InteractionResponse();
        }
        public void ProcessConsentAsync_PromptModeIsLogin_Throws()
        {
            RequiresConsent(true);
            var request = new ValidatedAuthorizeRequest()
            {
                ResponseMode = Constants.ResponseModes.Fragment,
                State = "12345",
                RedirectUri = new Uri("https://client.com/callback"),
                PromptMode = Constants.PromptModes.Login
            };

            try
            {
                var result = subject.ProcessConsentAsync(request).Result;
                Assert.Fail();
            }
            catch (AggregateException ex)
            {
                var ex2 = ex.InnerException;
                StringAssert.Contains(ex2.Message, "PromptMode");
            }
        }