Exemplo n.º 1
0
        public async Task <JwtViewModel> RefreshTokenAsync(JwtViewModel jwtViewModel)
        {
            var jwtSettingsSection        = _configuration.GetSection("JwtSettings");
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidateIssuer   = true,
                ValidIssuer      = jwtSettingsSection.GetValue(typeof(string), "Issuer").ToString(),
                ValidateLifetime = false,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettingsSection.GetValue(typeof(string), "Secret").ToString()))
            };
            var           tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken token;
            var           validateTokenResult = tokenHandler.ValidateToken(jwtViewModel.Token, tokenValidationParameters, out token);
            var           userEmailClaim      = validateTokenResult.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Email);
            var           jwtSecurityToken    = token as JwtSecurityToken;

            if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new SecurityTokenException("Invalid token");
            }
            var user = await _userManager.FindByEmailAsync(userEmailClaim.Value);

            if (user != null)
            {
                return(await GenerateJwtAsync(user));
            }
            return(null);
        }
Exemplo n.º 2
0
        /// <summary>
        ///     <inheritdoc />
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public JwtViewModel GenerateJwt(User user)
        {
            // Find current time on the system.
            var systemTime    = DateTime.Now;
            var jwtExpiration = systemTime.AddSeconds(_appJwt.LifeTime);

            // Claims initalization.
            var claims = new List <Claim>();

            claims.Add(new Claim(JwtRegisteredClaimNames.Aud, _appJwt.Audience));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iss, _appJwt.Issuer));
            claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
            claims.Add(new Claim(nameof(user.Nickname), user.Nickname));
            claims.Add(new Claim(nameof(user.Id), user.Id.ToString()));

            // Write a security token.
            var jwtSecurityToken = new JwtSecurityToken(_appJwt.Issuer, _appJwt.Audience, claims,
                                                        null, jwtExpiration, _appJwt.SigningCredentials);

            // Initiate token handler which is for generating token code.
            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();

            jwtSecurityTokenHandler.WriteToken(jwtSecurityToken);

            // Initialize jwt response.
            var jwt = new JwtViewModel();

            jwt.AccessToken = jwtSecurityTokenHandler.WriteToken(jwtSecurityToken);
            jwt.LifeTime    = _appJwt.LifeTime;
            jwt.Expiration  = _baseTimeService.DateTimeUtcToUnix(jwtExpiration);

            //_profileCacheService.Add(user.Id, user, LifeTimeConstant.JwtLifeTime);
            return(jwt);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> RefreshTokenAsync([FromBody] JwtViewModel jwtViewModel)
        {
            var claims = Request.HttpContext.User.Identity.Name;

            try
            {
                var result = await _userService.RefreshTokenAsync(jwtViewModel);

                if (result != null)
                {
                    return(Ok(result));
                }
                return(NotFound(new { error = "Nie znaleziono takiego użytkownika" }));
            }
            catch (SecurityTokenException ex)
            {
                return(BadRequest(new { error = ex.Message }));
            }
        }
Exemplo n.º 4
0
 public static void SetJwt(this IMemoryCache cache, Guid TokenId, JwtViewModel jwt)
 => cache.Set(GetJwtKey(TokenId), jwt, TimeSpan.FromSeconds(5));