Example #1
0
        public async Task <Token> IssueTokenAsync(LoginUserInfo loginUserInfo)
        {
            if (loginUserInfo == null)
            {
                throw new ArgumentNullException(nameof(loginUserInfo));
            }

            var signinCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecurityKey)), SecurityAlgorithms.HmacSha256);

            var tokeOptions = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: new List <Claim>()
            {
                new Claim(AuthConstants.JwtClaimTypes.Subject, loginUserInfo.Id.ToString()),
                new Claim(AuthConstants.JwtClaimTypes.Name, loginUserInfo.Name)
            },
                expires: DateTime.Now.AddSeconds(_jwtOptions.Expires),
                signingCredentials: signinCredentials
                );


            var refreshToken = new PersistedGrant()
            {
                UserId       = loginUserInfo.Id,
                Type         = "refresh_token",
                CreationTime = DateTime.Now,
                RefreshToken = Guid.NewGuid().ToString("N"),
                Expiration   = DateTime.Now.AddSeconds(_jwtOptions.RefreshTokenExpires)
            };

            _dc.AddEntity(refreshToken);
            await _dc.SaveChangesAsync();

            return(await Task.FromResult(new Token()
            {
                AccessToken = new JwtSecurityTokenHandler().WriteToken(tokeOptions),
                ExpiresIn = _jwtOptions.Expires,
                TokenType = AuthConstants.JwtTokenType,
                RefreshToken = refreshToken.RefreshToken
            }));
        }