示例#1
0
        private dynamic GenerateTokenModel(IdentityUser user, ICollection <Claim> claims = null)
        {
            if (user == null)
            {
                _logger.LogWarning("Null user passed to " + nameof(GenerateTokenModel));
                return(new TokenModel());
            }

            var roles = _context.GetRolesForUser(user);

            claims ??= new List <Claim>();
            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            string accessToken;

            try
            {
                accessToken = _jwtTokenGenerator.GenerateAccessToken(user, claims);
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Failed to generate access token for user {username} with userid {userid}. TokenOptions not setup correctly.",
                                    user.UserName, user.Id);
                ModelState.AddModelError("TokenError", $"Unable to login to the system at the moment. Please try later.");
                return(new TokenModel());
            }

            var tokenModel = new TokenModel
            {
                AccessToken       = accessToken,
                Username          = user.UserName,
                UserId            = user.Id,
                RequiresTwoFactor = user.TwoFactorEnabled
            };

            return(tokenModel);
        }