/// <summary>
        /// Creates the asynchronous.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

            if (string.IsNullOrEmpty(clientid))
            {
                return;
            }

            var refreshTokenId = Guid.NewGuid().ToString("n");
            var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");

            var token = new Domain.Entities.RefreshToken()
            {
                Id = CryptHelper.GetHash(refreshTokenId),
                ClientId = clientid,
                Subject = context.Ticket.Identity.Name,
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };

            context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

            token.ProtectedTicket = context.SerializeTicket();

            var result = await _auth.AddRefreshToken(token);

            if (result)
            {
                context.SetToken(refreshTokenId);
            }

        }
Exemplo n.º 2
0
        public async Task <IdentityResponseDto> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            ApplicationUser user = await _userManager.FindByNameAsync(request.UserName, x => x.RefreshTokens);

            if (user == null)
            {
                return(IdentityResponseDto.NotExisted($"User with {request.UserName} not existed."));
            }

            if (!await _userManager.IsEmailConfirmedAsync(user))
            {
                return(IdentityResponseDto.EmailNotConfirmed($"You need to confirm your email."));
            }

            if (await _userManager.IsLockedOutAsync(user))
            {
                return(IdentityResponseDto.LockedOut($"Account has been locked."));
            }

            if (await _userManager.CheckPasswordAsync(user, request.Password))
            {
                JwtSecurityToken jwtSecurityToken = await _tokenClaimService.GenerateTokenAsync(user);

                var response = new IdentityResponseDto
                {
                    Status   = LoginStatus.Success,
                    Token    = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
                    Email    = user.Email,
                    UserName = user.UserName,
                    Roles    = (await _userManager.GetRolesAsync(user)).ToList(),
                    Message  = "Success."
                };

                Domain.Entities.RefreshToken activeRefreshToken = user.RefreshTokens.FirstOrDefault(x => x.IsActive);
                if (activeRefreshToken is null)
                {
                    activeRefreshToken = _tokenClaimService.GenerateRefreshToken();
                    user.RefreshTokens.Add(activeRefreshToken);
                    await _userManager.UpdateAsync(user);
                }

                response.RefreshToken           = activeRefreshToken.Token;
                response.RefreshTokenExpiration = activeRefreshToken.Expires;

                _logger.LogInformation($"User {user.UserName} login success.");

                await _mediator.Publish(new LoginSuccessEvent
                {
                    UserName       = user.UserName,
                    LoginSuccessAt = DateTimeOffset.UtcNow
                }, cancellationToken);

                return(response);
            }

            return(IdentityResponseDto.Failure($"Incorrect Credentials for user {user.UserName}."));
        }
Exemplo n.º 3
0
            public async Task <ICommandQueryResponse> Handle(Command request, CancellationToken cancellationToken)
            {
                var data = new Domain.Entities.RefreshToken
                {
                    UserID          = request.RefreshTokenModel.AppUserID,
                    Token           = request.RefreshTokenModel.Token,
                    Expires         = request.RefreshTokenModel.Expires,
                    Created         = request.RefreshTokenModel.Created,
                    CreatedByIp     = request.RefreshTokenModel.CreatedByIp,
                    Revoked         = request.RefreshTokenModel.Revoked,
                    RevokedByIp     = request.RefreshTokenModel.RevokedByIp,
                    ReplacedByToken = request.RefreshTokenModel.ReplacedByToken
                };

                _dataContext.RefreshToken.Add(data);
                await _dataContext.SaveChangesAsync();

                return(new CreateRefreshTokenResponse(request.RefreshTokenModel));
            }
        public async Task <IdentityResponseDto> Handle(RefreshTokenCommand request, CancellationToken cancellationToken)
        {
            ApplicationUser user = await _userManager.FindByRefreshTokenAsync(request.Token, x => x.RefreshTokens);

            if (user is null)
            {
                return(IdentityResponseDto.NotExisted($"Token {request.Token} did not match with nay user."));
            }

            var activeRefreshToken = user.RefreshTokens
                                     .FirstOrDefault(x => x.Token == request.Token && x.IsActive);

            if (activeRefreshToken is null)
            {
                return(IdentityResponseDto.Failure($"Token {request.Token} not active."));
            }

            // Revoke current token
            activeRefreshToken.RevokedDate = DateTime.UtcNow;
            // Generate new token and refresh token
            Domain.Entities.RefreshToken newRefreshToken = _tokenClaimService.GenerateRefreshToken();
            user.RefreshTokens.Add(newRefreshToken);
            await _userManager.UpdateAsync(user);

            JwtSecurityToken jwtSecurityToken = await _tokenClaimService.GenerateTokenAsync(user);

            return(new IdentityResponseDto
            {
                Status = LoginStatus.Success,
                Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
                Email = user.Email,
                UserName = user.UserName,
                Roles = (await _userManager.GetRolesAsync(user)).ToList(),
                Message = "Success.",
                RefreshToken = newRefreshToken.Token,
                RefreshTokenExpiration = newRefreshToken.Expires
            });
        }