Exemplo n.º 1
0
        public string Create(string login)
        {
            var now     = DateTime.UtcNow;
            var expire  = now.Add(_options.REFRESH_LIFETIME);
            var tokenId = $"{Guid.NewGuid()}_{login}";
            var token   = new JwtSecurityToken(
                audience: tokenId,
                issuer: _options.ISSUER,
                notBefore: now,
                expires: expire,
                signingCredentials: new SigningCredentials(_options.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

            _refreshTokenDAL.Add(new RefreshToken
            {
                Audience = tokenId,
                Expire   = expire,
                Token    = tokenString,
            });

            return(tokenString);
        }
Exemplo n.º 2
0
        public AccessTokenData CreateJwt(User user, string refresh_token)
        {
            var now = DateTime.UtcNow;

            //создаем список Claim-ов
            var claims = new List <Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login)
            };

            //получаем список ролей пользователя и добавляем их в список Claim-ов
            var roles = user.UserRoles.Select(u => u.Role).ToList();

            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, role.Title));
            }

            var expires = now.Add(_options.ACCESS_LIFETIME);
            // создаем JWT-токен
            var jwt = new JwtSecurityToken(
                issuer: _options.ISSUER,
                audience: _options.AUDIENCE,
                notBefore: now,
                claims: claims,
                expires: expires,
                signingCredentials: new SigningCredentials(_options.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new AccessTokenData
            {
                AccessToken = encodedJwt,
                ExpiresIn = expires.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds,
            });
        }