Пример #1
0
        /// <inheritdoc />
        public async Task <IUserActionResult> Create(T user, string password)
        {
            var identityResult = await _userManager.CreateAsync(user, password);

            if (identityResult.Errors.Any())
            {
                return(new DefaultUserActionResultBuilder()
                       .WithIdentityErrors(identityResult.Errors)
                       .Build());
            }

            //Generate tokens for the user
            var jwt          = _jwtHandler.Generate(DefaultJwtHandler.GetDefaultClaims(user.FirstName, user.Email));
            var refreshToken = _refreshTokenGenerator.Generate();

            //Add token to db and update user
            user.RefreshTokens.Add(refreshToken);
            await _userManager.UpdateAsync(user);

            return(new DefaultUserActionResultBuilder()
                   .Success()
                   .WithJwt(jwt)
                   .WithRefreshToken(refreshToken.Token)
                   .Build());
        }
Пример #2
0
            public async Task <AuthUserDTO> Handle(Command request, CancellationToken cancellationToken)
            {
                var user = await dataContext.Users.FirstOrDefaultAsync(x => x.UserName == request.UserName);

                if (user is null)
                {
                    throw new HttpContextException(HttpStatusCode.BadRequest, new { User = "******" });
                }

                var result = await signInManager.CheckPasswordSignInAsync(user, request.Password, false);

                if (result.Succeeded)
                {
                    var refreshToken = refreshTokenGenerator.Generate(user.UserName);

                    await authCookies.SendAuthCookies(user, refreshToken);

                    var key = "rid-" + Convert.ToBase64String(Encoding.UTF8.GetBytes(user.UserName));
                    await cache.SetRefreshToken(key, refreshToken);

                    return(new AuthUserDTO(user));
                }
                else
                {
                    throw new HttpContextException(HttpStatusCode.BadRequest, new { User = "******" });
                }
                throw new Exception("Server Error -Login");
            }
Пример #3
0
            public async Task <AuthUserDTO> Handle(Command request, CancellationToken cancellationToken)
            {
                var isExist = await dataContext.Users.FirstOrDefaultAsync(x => x.UserName == request.UserName) != null;

                if (isExist)
                {
                    throw new HttpContextException(HttpStatusCode.BadRequest, new { User = "******" });
                }

                var user = new AppUser
                {
                    FirstName = request.FirstName,
                    LastName  = request.LastName,
                    UserName  = request.UserName,
                    Email     = request.Email
                };
                var registerResult = await userManager.CreateAsync(user, request.Password);

                var roleResult = await userManager.AddToRoleAsync(user, "Normal");

                if (registerResult.Succeeded && roleResult.Succeeded)
                {
                    var refreshToken = refreshTokenGenerator.Generate(user.UserName);

                    await authCookies.SendAuthCookies(user, refreshToken);

                    var key = "rid-" + Convert.ToBase64String(Encoding.UTF8.GetBytes(user.UserName));
                    await cache.SetRefreshToken(key, refreshToken);

                    return(new AuthUserDTO(user));
                }
                throw new Exception("Server Error - Register");
            }
        public async Task <IActionResult> SignIn([FromBody] LoginViewModel loginViewModel)
        {
            var user = await _userManager.FindByEmailAsync(loginViewModel.Email);

            if (user == null)
            {
                return(new NotFoundResult());
            }
            var result = await _signInManager.CheckPasswordSignInAsync(user, loginViewModel.Password, false);

            if (result.Succeeded)
            {
                var token = new JwtTokenViewModel
                {
                    AccessToken  = _jwtTokenGenerator.Generate(user),
                    RefreshToken = _refreshTokenGenerator.Generate()
                };

                try
                {
                    await _tokenProvider.RegisterRefreshToken(token.RefreshToken, user.Id);

                    await _tokenProvider.RegisterAccessToken(
                        _jwtTokenHelper.GetSignature(token.AccessToken),
                        _jwtTokenHelper.GetExpirationDate(token.AccessToken),
                        user.Id);
                }
                catch (Exception)
                {
                    return(new StatusCodeResult((int)HttpStatusCode.InternalServerError));
                }

                return(new OkObjectResult(token));
            }

            if (result.IsLockedOut || result.IsNotAllowed)
            {
                return(new ForbidResult());
            }

            return(new ForbidResult());
        }
        public async Task <GResult <TokenModel> > RefreshTokenAsync(string expiredToken, string refreshToken)
        {
            ClaimsPrincipal principal = null;
            var             errors    = new List <GError>();

            // Validate Jwt Token
            try
            {
                var tokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jsonWebTokenOptions.Key)),
                    ValidIssuer              = _jsonWebTokenOptions.Issuer,
                    ValidAudience            = _jsonWebTokenOptions.Audience,
                    ValidateAudience         = !string.IsNullOrWhiteSpace(_jsonWebTokenOptions.Audience),
                    ValidateIssuer           = !string.IsNullOrWhiteSpace(_jsonWebTokenOptions.Issuer),
                    ValidateIssuerSigningKey = true,
                    ClockSkew        = TimeSpan.Zero,
                    ValidateLifetime = false
                };
                var tokenHandler = new JwtSecurityTokenHandler();
                principal = tokenHandler.ValidateToken(expiredToken, tokenValidationParameters, out var securityToken);

                if (!IsValidSecurityToken(securityToken))
                {
                    throw new SecurityTokenException("Invalid security token");
                }

                var expiryDateUnix    = long.Parse(principal.FindFirst(JwtClaimNames.Exp).Value);
                var expiryDateTimeUtc = DateTime.UnixEpoch.AddSeconds(expiryDateUnix);

                if (expiryDateTimeUtc > DateTime.UtcNow)
                {
                    return(GResult <TokenModel> .Success(new TokenModel { AccessToken = expiredToken, RefreshToken = refreshToken }));
                }
            }
            catch (SecurityTokenException ex)
            {
                errors.Add(ErrorDescriber.InvalidToken(ex.Message));
            }

            if (errors.Count > 0)
            {
                return(GResult <TokenModel> .Failed(errors.ToArray()));
            }
            // Validate Refresh Token
            else
            {
                var userId = Guid.Parse(principal?.FindFirst(ClaimTypes.NameIdentifier).Value);
                var jwtId  = principal?.FindFirstValue(JwtClaimNames.Jti);
                // Check if refresh token already registered for this user
                var readUserLoginResult = await base.ReadAsync(new FindUserLogin <UserLogin>(userId, jwtId, refreshToken));

                if (readUserLoginResult.Succeeded)
                {
                    var userLogin = readUserLoginResult.Outcome;
                    if (DateTime.UtcNow > userLogin.ExpiryDate)
                    {
                        await base.DeleteAsync(userLogin);

                        return(GResult <TokenModel> .Failed(ErrorDescriber.InvalidToken("")));
                    }
                    else
                    {
                        var readUserResult = await UserService.ReadAsync(new FindByIdSpec <User>(userId));

                        if (readUserResult.Succeeded)
                        {
                            var user   = readUserResult.Outcome;
                            var claims = await _userClaimsFactory.CreateAsync(user);

                            var newJwtId = claims.FirstOrDefault(c => c.Type == JwtClaimNames.Jti).Value;
                            var newToken = _jsonWebTokenCoder.Encode(claims);
                            userLogin.JwtId = newJwtId;
                            // Check if refresh token required update
                            if (DateTime.UtcNow > userLogin.RequiredUpdateDate)
                            {
                                userLogin.RefreshToken       = _refreshTokenGenerator.Generate(user);
                                userLogin.ExpiryDate         = DateTime.UtcNow + _jsonWebTokenOptions.RefreshToken.Expires;
                                userLogin.RequiredUpdateDate = DateTime.UtcNow + _jsonWebTokenOptions.RefreshToken.UpdateRequired;
                            }

                            var updateUserLoginResult = await base.UpdateAsync(userLogin);

                            if (!updateUserLoginResult.Succeeded)
                            {
                                return(GResult <TokenModel> .Failed(updateUserLoginResult.Errors.ToArray()));
                            }
                            return(GResult <TokenModel> .Success(new TokenModel { AccessToken = newToken, RefreshToken = userLogin.RefreshToken }));
                        }
                        else
                        {
                            return(GResult <TokenModel> .Failed(ErrorDescriber.InvalidCredentials()));
                        }
                    }
                }
                else
                {
                    return(GResult <TokenModel> .Failed(ErrorDescriber.InvalidCredentials()));
                }
            }
        }