コード例 #1
0
        public async Task <TokenResult> GenerateClaimsTokenAsync(string email, CancellationToken cancellationToken)
        {
            var user = await _userManager.FindByEmailAsync(email);

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(ClaimTypes.Email, email),
                    new Claim(JwtRegisteredClaimNames.Sub, email),
                    new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
                    new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddMinutes(5)).ToUnixTimeSeconds().ToString()),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                }),
                Expires            = DateTime.UtcNow.Add(_jwtSettings.Expiration),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var refreshToken = new RefreshToken
            {
                JwtId          = token.Id,
                UserId         = user.Id,
                Invalidated    = false,
                Used           = false,
                CreationDate   = DateTime.UtcNow,
                ExpirationDate = DateTime.UtcNow.AddMonths(3),
                Token          = GenerateRandomString(35) + Guid.NewGuid()
            };

            _dbContext.RefreshTokens.Add(refreshToken);
            await _dbContext.SaveChangesAsync(cancellationToken);

            return(new TokenResult()
            {
                Succeeded = true,
                AccessToken = tokenHandler.WriteToken(token),
                RefreshToken = refreshToken.Token
            });
        }
コード例 #2
0
            public async Task Handle(LoginEventNotification notification, CancellationToken cancellationToken)
            {
                var entity = new LoginAuditLog
                {
                    Username    = notification.Username,
                    Description = notification.Description,
                    IsSuccess   = notification.IsSuccess,
                    IpAddress   = notification.IpAddress,
                    Timestamp   = notification.Timestamp
                };

                _dbContext.LoginAuditLogs.Add(entity);

                await _dbContext.SaveChangesAsync(cancellationToken);
            }