Ejemplo n.º 1
0
        public async Task When_Pass_Null_Parameters_Then_Exceptions_Are_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();

            // ACTS & ASSERTS
            await Assert.ThrowsAsync <ArgumentNullException>(() => _resourceOwnerAuthenticateHelper.Authenticate(null, null, null));

            await Assert.ThrowsAsync <ArgumentNullException>(() => _resourceOwnerAuthenticateHelper.Authenticate("login", null, null));
        }
        public async Task <LoginPwdAuthenticateResult> Execute(LoginPasswordAuthParameter parameter, AuthorizationParameter authorizationParameter, string code, string issuerName)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (authorizationParameter == null)
            {
                throw new ArgumentNullException(nameof(authorizationParameter));
            }


            var resourceOwner = await _resourceOwnerAuthenticateHelper.Authenticate(parameter.Login, parameter.Password, new[] { Constants.AMR }).ConfigureAwait(false);

            if (resourceOwner == null)
            {
                throw new IdentityServerAuthenticationException("the resource owner credentials are not correct");
            }

            var claims = resourceOwner.Claims == null ? new List <Claim>() : resourceOwner.Claims.ToList();

            claims.Add(new Claim(ClaimTypes.AuthenticationInstant, DateTimeOffset.UtcNow.ConvertToUnixTimestamp().ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer));
            return(new LoginPwdAuthenticateResult
            {
                ActionResult = await _authenticateHelper.ProcessRedirection(authorizationParameter, code, resourceOwner.Id, claims, issuerName).ConfigureAwait(false),
                Claims = claims
            });
        }
        /// <summary>
        /// Authenticate local user account.
        /// Exceptions :
        /// Throw the exception <see cref="IdentityServerAuthenticationException "/> if the user cannot be authenticated
        /// </summary>
        /// <param name="localAuthenticationParameter">User's credentials</param>
        /// <param name="authorizationParameter">Authorization parameters</param>
        /// <param name="code">Encrypted & signed authorization parameters</param>
        /// <param name="claims">Returned the claims of the authenticated user</param>
        /// <returns>Consent screen or redirect to the Index page.</returns>
        public async Task <LocalOpenIdAuthenticationResult> Execute(
            LocalAuthenticationParameter localAuthenticationParameter,
            AuthorizationParameter authorizationParameter,
            string code, string issuerName)
        {
            if (localAuthenticationParameter == null)
            {
                throw new ArgumentNullException(nameof(localAuthenticationParameter));
            }

            if (authorizationParameter == null)
            {
                throw new ArgumentNullException(nameof(authorizationParameter));
            }

            var resourceOwner = await _resourceOwnerAuthenticateHelper.Authenticate(localAuthenticationParameter.UserName, localAuthenticationParameter.Password, authorizationParameter.AmrValues);

            if (resourceOwner == null)
            {
                throw new IdentityServerAuthenticationException("the resource owner credentials are not correct");
            }

            var claims = resourceOwner.Claims == null ? new List <Claim>() : resourceOwner.Claims.ToList();

            claims.Add(new Claim(ClaimTypes.AuthenticationInstant,
                                 DateTimeOffset.UtcNow.ConvertToUnixTimestamp().ToString(CultureInfo.InvariantCulture),
                                 ClaimValueTypes.Integer));
            return(new LocalOpenIdAuthenticationResult
            {
                ActionResult = await _authenticateHelper.ProcessRedirection(authorizationParameter,
                                                                            code,
                                                                            resourceOwner.Id,
                                                                            claims, issuerName),
                Claims = claims,
                TwoFactor = resourceOwner.TwoFactorAuthentication
            });
        }
Ejemplo n.º 4
0
        public async Task <ActionResult> LocalLogin(LocalAuthenticationViewModel authorizeViewModel)
        {
            var authenticatedUser = await SetUser();

            if (authenticatedUser != null &&
                authenticatedUser.Identity != null &&
                authenticatedUser.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "User", new { area = "UserManagement" }));
            }

            if (authorizeViewModel == null)
            {
                throw new ArgumentNullException(nameof(authorizeViewModel));
            }

            if (!ModelState.IsValid)
            {
                await TranslateView(DefaultLanguage);

                var viewModel = new AuthorizeViewModel();
                await SetIdProviders(viewModel);

                return(View("Index", viewModel));
            }

            try
            {
                var resourceOwner = await _resourceOwnerAuthenticateHelper.Authenticate(authorizeViewModel.Login, authorizeViewModel.Password, new[] { Constants.AMR });

                if (resourceOwner == null)
                {
                    throw new IdentityServerAuthenticationException("the resource owner credentials are not correct");
                }

                var claims = resourceOwner.Claims;
                claims.Add(new Claim(ClaimTypes.AuthenticationInstant,
                                     DateTimeOffset.UtcNow.ConvertToUnixTimestamp().ToString(CultureInfo.InvariantCulture),
                                     ClaimValueTypes.Integer));
                var subject = claims.First(c => c.Type == Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject).Value;
                if (string.IsNullOrWhiteSpace(resourceOwner.TwoFactorAuthentication))
                {
                    await SetLocalCookie(claims, Guid.NewGuid().ToString());

                    _simpleIdentityServerEventSource.AuthenticateResourceOwner(subject);
                    return(RedirectToAction("Index", "User", new { area = "UserManagement" }));
                }

                // 2.1 Store temporary information in cookie
                await SetTwoFactorCookie(claims);

                // 2.2. Send confirmation code
                try
                {
                    var code = await _authenticateActions.GenerateAndSendCode(subject);

                    _simpleIdentityServerEventSource.GetConfirmationCode(code);
                    return(RedirectToAction("SendCode"));
                }
                catch (ClaimRequiredException)
                {
                    return(RedirectToAction("SendCode"));
                }
                catch (Exception)
                {
                    throw new Exception("Two factor authenticator is not properly configured");
                }
            }
            catch (Exception exception)
            {
                _simpleIdentityServerEventSource.Failure(exception.Message);
                await TranslateView(DefaultLanguage);

                ModelState.AddModelError("invalid_credentials", exception.Message);
                var viewModel = new AuthorizeViewModel();
                await SetIdProviders(viewModel);

                return(View("Index", viewModel));
            }
        }
Ejemplo n.º 5
0
        public async Task <GrantedToken> Execute(ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate, string issuerName)
        {
            if (resourceOwnerGrantTypeParameter == null)
            {
                throw new ArgumentNullException(nameof(resourceOwnerGrantTypeParameter));
            }

            // 1. Try to authenticate the client
            var instruction = CreateAuthenticateInstruction(resourceOwnerGrantTypeParameter, authenticationHeaderValue, certificate);
            var authResult  = await _authenticateClient.AuthenticateAsync(instruction, issuerName);

            var client = authResult.Client;

            if (authResult.Client == null)
            {
                _oauthEventSource.Info(authResult.ErrorMessage);
                throw new IdentityServerException(ErrorCodes.InvalidClient, authResult.ErrorMessage);
            }

            // 2. Check the client.
            if (client.GrantTypes == null || !client.GrantTypes.Contains(GrantType.password))
            {
                throw new IdentityServerException(ErrorCodes.InvalidClient,
                                                  string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, client.ClientId, GrantType.password));
            }

            if (client.ResponseTypes == null || !client.ResponseTypes.Contains(ResponseType.token) || !client.ResponseTypes.Contains(ResponseType.id_token))
            {
                throw new IdentityServerException(ErrorCodes.InvalidClient, string.Format(ErrorDescriptions.TheClientDoesntSupportTheResponseType, client.ClientId, "token id_token"));
            }

            // 3. Try to authenticate a resource owner
            var resourceOwner = await _resourceOwnerAuthenticateHelper.Authenticate(resourceOwnerGrantTypeParameter.UserName,
                                                                                    resourceOwnerGrantTypeParameter.Password,
                                                                                    resourceOwnerGrantTypeParameter.AmrValues);

            if (resourceOwner == null)
            {
                throw new IdentityServerException(ErrorCodes.InvalidGrant, ErrorDescriptions.ResourceOwnerCredentialsAreNotValid);
            }

            // 4. Check if the requested scopes are valid
            var allowedTokenScopes = string.Empty;

            if (!string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.Scope))
            {
                var scopeValidation = _scopeValidator.Check(resourceOwnerGrantTypeParameter.Scope, client);
                if (!scopeValidation.IsValid)
                {
                    throw new IdentityServerException(ErrorCodes.InvalidScope, scopeValidation.ErrorMessage);
                }

                allowedTokenScopes = string.Join(" ", scopeValidation.Scopes);
            }

            // 5. Generate the user information payload and store it.
            var claims                 = resourceOwner.Claims;
            var claimsIdentity         = new ClaimsIdentity(claims, "simpleIdentityServer");
            var claimsPrincipal        = new ClaimsPrincipal(claimsIdentity);
            var authorizationParameter = new AuthorizationParameter
            {
                Scope = resourceOwnerGrantTypeParameter.Scope
            };
            var payload = await _jwtGenerator.GenerateIdTokenPayloadForScopesAsync(claimsPrincipal, authorizationParameter, issuerName);

            var generatedToken = await _grantedTokenHelper.GetValidGrantedTokenAsync(allowedTokenScopes, client.ClientId, payload, payload);

            if (generatedToken == null)
            {
                generatedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync(client, allowedTokenScopes, issuerName, payload, payload);

                if (generatedToken.IdTokenPayLoad != null)
                {
                    await _jwtGenerator.UpdatePayloadDate(generatedToken.IdTokenPayLoad);

                    generatedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(client, generatedToken.IdTokenPayLoad);
                }

                await _tokenStore.AddToken(generatedToken);

                _oauthEventSource.GrantAccessToClient(client.ClientId, generatedToken.AccessToken, allowedTokenScopes);
            }

            return(generatedToken);
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> ConfirmCode(ConfirmCodeViewModel confirmCodeViewModel)
        {
            if (confirmCodeViewModel == null)
            {
                throw new ArgumentNullException(nameof(confirmCodeViewModel));
            }

            if (string.IsNullOrWhiteSpace(confirmCodeViewModel.Code))
            {
                throw new ArgumentNullException(nameof(confirmCodeViewModel.Code));
            }

            var user = await SetUser().ConfigureAwait(false);

            if (user != null && user.Identity != null && user.Identity.IsAuthenticated)
            {
                return(new UnauthorizedResult());
            }

            var authenticatedUser = await _authenticationService.GetAuthenticatedUser(this, Host.Constants.CookieNames.PasswordLessCookieName).ConfigureAwait(false);

            if (authenticatedUser == null || authenticatedUser.Identity == null || !authenticatedUser.Identity.IsAuthenticated)
            {
                throw new IdentityServerException(ErrorCodes.UnhandledExceptionCode, "SMS authentication cannot be performed");
            }

            var subject     = authenticatedUser.Claims.First(c => c.Type == Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject).Value;
            var phoneNumber = authenticatedUser.Claims.First(c => c.Type == Core.Jwt.Constants.StandardResourceOwnerClaimNames.PhoneNumber);

            if (confirmCodeViewModel.Action == "resend") // Resend the confirmation code.
            {
                var code = await _generateAndSendSmsCodeOperation.Execute(phoneNumber.Value).ConfigureAwait(false);
                await TranslateView(DefaultLanguage).ConfigureAwait(false);

                return(View("ConfirmCode", confirmCodeViewModel));
            }

            ResourceOwner resourceOwner;

            try
            {
                resourceOwner = await _resourceOwnerAuthenticateHelper.Authenticate(phoneNumber.Value, confirmCodeViewModel.ConfirmationCode, new[] { Constants.AMR }).ConfigureAwait(false);
            }
            catch (Exception)
            {
                ModelState.AddModelError("message_error", "Confirmation code is not valid");
                await TranslateView(DefaultLanguage).ConfigureAwait(false);

                return(View("ConfirmCode", confirmCodeViewModel));
            }

            await _authenticationService.SignOutAsync(HttpContext, Host.Constants.CookieNames.PasswordLessCookieName, new AuthenticationProperties()).ConfigureAwait(false);

            var request      = _dataProtector.Unprotect <AuthorizationRequest>(confirmCodeViewModel.Code);
            var issuerName   = Request.GetAbsoluteUriWithVirtualPath();
            var actionResult = await _authenticateHelper.ProcessRedirection(request.ToParameter(), confirmCodeViewModel.Code, subject, authenticatedUser.Claims.ToList(), issuerName).ConfigureAwait(false);

            if (actionResult.AmrLst != null)
            {
                request.AmrValues = string.Join(" ", actionResult.AmrLst);
            }

            if (actionResult.Type == Core.Results.TypeActionResult.RedirectToAction && actionResult.RedirectInstruction.Action == Core.Results.IdentityServerEndPoints.AuthenticateIndex)
            {
                var encryptedRequest = _dataProtector.Protect(request);
                actionResult.RedirectInstruction.AddParameter(Core.Constants.StandardAuthorizationResponseNames.AuthorizationCodeName, encryptedRequest);
                await SetAcrCookie(authenticatedUser.Claims).ConfigureAwait(false);

                return(this.CreateRedirectionFromActionResult(actionResult, request));
            }

            await _authenticationService.SignOutAsync(HttpContext, Host.Constants.CookieNames.AcrCookieName, new AuthenticationProperties()).ConfigureAwait(false);

            await SetLocalCookie(authenticatedUser.Claims, request.SessionId).ConfigureAwait(false);

            var result = this.CreateRedirectionFromActionResult(actionResult, request);

            LogAuthenticateUser(actionResult, request.ProcessId);
            return(result);
        }