コード例 #1
0
        /// <summary>
        /// Executes the command
        /// </summary>
        /// <returns>authentication result</returns>
        public async Task <AuthenticateUserResultModel> Execute(AuthenticateUserInputModel model)
        {
            // Check access rights: Anonymous
            accessRightChecker.CheckUserIsAnonymous();

            // pretreatment of model
            model.CheckAndPrepare();

            string passwordHash = HashHelper.GetHashString(model.Password);

            // Checks that user exists
            User user = await userRepository.FirstOrDefaultAsync(iu => iu.Email == model.UserName && iu.PasswordHash == passwordHash);

            if (user is null)
            {
                throw new BusinessException("User with this login and password does not exist");
            }

            var userRole = user.IsAdmin ? UserRole.Admin : UserRole.User;
            // Adding claims
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, model.UserName),      // login
                new Claim(ClaimsIdentity.DefaultRoleClaimType, userRole.ToString()), // role
                new Claim(ClaimTypes.Sid, user.AuthenticationTokenId.ToString())
            };

            // Generating a token
            var jwt = new JwtSecurityToken(
                issuer: AuthOptions.Issuer,
                audience: AuthOptions.Audience,
                notBefore: DateTime.UtcNow,
                claims: claims,
                signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new AuthenticateUserResultModel
            {
                AccessToken = encodedJwt,
                Name = user.Name,
                UserName = model.UserName,
                Role = userRole
            });
        }
コード例 #2
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateUserInputModel authenticateUserInputModel)
        {
            var authorization = await _loginAppService.Authenticate(authenticateUserInputModel);

            return(Response(authorization));
        }
コード例 #3
0
 public async Task <Authorization> Authenticate(AuthenticateUserInputModel authenticateUserInputModel)
 {
     return(await _mediatorService.SendCommand(_mapper.Map <AuthenticateUserCommand>(authenticateUserInputModel)));
 }