Beispiel #1
0
        private IList <Claim> GenerateUserClaims(Entity.User user, IList <string> roles, AuthenticationFlow authenticationFlow)
        {
            try
            {
                var claims = new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
                };

                if (authenticationFlow.Equals(AuthenticationFlow.Full))
                {
                    var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r));
                    claims.AddRange(roleClaims);
                }

                return(claims);
            }
            catch (Exception ex)
            {
                logger.LogError($"Claims could not be generated for user: {user.Id}", ex);
                throw;
            }
        }
Beispiel #2
0
        private async Task <string> GenerateAccessToken(Entity.User user, AuthenticationFlow authenticationFlow)
        {
            try
            {
                var roles = await userManager.GetRolesAsync(user);

                if (roles is null)
                {
                    return(null);
                }

                var claims = GenerateUserClaims(user, roles, authenticationFlow);

                if (claims is null)
                {
                    return(null);
                }

                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Secret));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    issuer: tokenSettings.Issuer,
                    audience: tokenSettings.Issuer,
                    claims,
                    expires: DateTime.Now.AddDays(Convert.ToDouble(tokenSettings.AccessTokenExpirationInDays)),
                    signingCredentials: creds
                    );

                return(new JwtSecurityTokenHandler().WriteToken(token));
            }
            catch (Exception ex)
            {
                logger.LogError($"Generating access token for user: {user.Id} was not successfull", ex);
                throw;
            }
        }
Beispiel #3
0
        public async Task <Result <AuthenticationToken> > GenerateAuthenticationTokenAsync(Entity.User user, string loginProvider, AuthenticationFlow authenticationFlow)
        {
            try
            {
                var accessToken = await GenerateAccessToken(user, authenticationFlow);

                if (accessToken is null)
                {
                    return(new InvalidResult <AuthenticationToken>("Could not generate access token"));
                }

                var refreshToken = GenerateRefreshToken();

                if (refreshToken is null)
                {
                    return(new InvalidResult <AuthenticationToken>("Could not generate access token"));
                }

                var refreshTokenExpiration = DateTime.Now.AddDays(Convert.ToDouble(tokenSettings.RefreshTokenExpirationInDays));
                var accessTokenExpiration  = DateTime.Now.AddDays(Convert.ToDouble(tokenSettings.AccessTokenExpirationInDays));

                var token = await repository.AddUserTokenAsync(new UserToken()
                {
                    UserId                 = user.Id,
                    User                   = user,
                    LoginProvider          = loginProvider,
                    AccessToken            = accessToken,
                    RefreshToken           = refreshToken,
                    RefreshTokenExpiration = refreshTokenExpiration,
                    AccessTokenExpiration  = accessTokenExpiration,
                    AuthenticationFlow     = (int)authenticationFlow,
                });

                if (token is null)
                {
                    return(new InvalidResult <AuthenticationToken>("Could not save new authentication token"));
                }

                var result = mapper.Map <UserToken, AuthenticationToken>(token);

                return(new SuccessResult <AuthenticationToken>(result));
            }
            catch (Exception ex)
            {
                return(new UnexpectedResult <AuthenticationToken>(ex.Message));
            }
        }