Example #1
0
        public async Task Invoke(HttpContext httpContext, IOptions <JwtBearerTokenSettings> jwtTokenOptions, UserManager <User> userMgr, RefreshTokenRepository refreshTokenRepository)
        {
            string accessToken  = httpContext.Request.Cookies["accessToken"];
            string refreshToken = httpContext.Request.Cookies["refreshToken"];

            httpContext.Items["accessToken"] = httpContext.Request.Cookies["accessToken"];


            if (accessToken != null && refreshToken != null)
            {
                var tokenHandler       = new JwtSecurityTokenHandler();
                JwtSecurityToken token = tokenHandler.ReadJwtToken(accessToken);
                var expDate            = token.ValidTo;


                if (expDate < DateTime.UtcNow)
                {
                    var          nameid       = token.Claims.Where(c => c.Type == "nameid").FirstOrDefault();
                    RefreshToken refresh      = refreshTokenRepository.GetByUserIdAndToken(nameid.Value, refreshToken);
                    User         identityUser = await userMgr.FindByIdAsync(nameid.Value);

                    if (refresh != null)
                    {
                        if (refresh.ExpiryOn < DateTime.UtcNow || identityUser.IsLocked == true)
                        {
                            await refreshTokenRepository.Remove(refresh.Id);

                            // Set Token Cookie
                            var cookieOptions = new CookieOptions
                            {
                                HttpOnly = true,
                                Secure   = true,
                                SameSite = SameSiteMode.None,
                                Expires  = DateTime.UtcNow.AddDays(-1)
                            };
                            httpContext.Response.Cookies.Append("accessToken", "", cookieOptions);
                            httpContext.Response.Cookies.Append("refreshToken", "", cookieOptions);
                            httpContext.Items["accessToken"] = "";
                        }
                        else
                        {
                            var key         = Encoding.UTF8.GetBytes(jwtTokenOptions.Value.SecretKey);
                            var unique_name = token.Claims.Where(c => c.Type == "unique_name").FirstOrDefault();
                            var email       = token.Claims.Where(c => c.Type == "email").FirstOrDefault();
                            var role        = token.Claims.Where(c => c.Type == "role").FirstOrDefault();

                            var tokenDescriptor = new SecurityTokenDescriptor
                            {
                                Subject = new ClaimsIdentity(new Claim[]
                                {
                                    new Claim(ClaimTypes.NameIdentifier, nameid.Value),
                                    new Claim(ClaimTypes.Name, unique_name.Value),
                                    new Claim(ClaimTypes.Email, email.Value),
                                    new Claim(ClaimTypes.Role, role.Value)
                                }),

                                Expires            = DateTime.UtcNow.AddSeconds(jwtTokenOptions.Value.ExpiryTimeInSeconds),
                                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                                Audience           = jwtTokenOptions.Value.Audience,
                                Issuer             = jwtTokenOptions.Value.Issuer
                            };

                            // Set Access Token Cookie
                            var accessTokenCookieOptions = new CookieOptions
                            {
                                HttpOnly = true,
                                Secure   = true,
                                SameSite = SameSiteMode.None
                                           //Expires = DateTime.UtcNow.AddDays(7)
                            };
                            httpContext.Response.Cookies.Append("accessToken", tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)), accessTokenCookieOptions);
                            httpContext.Items["accessToken"] = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
                        }
                    }
                }
            }

            //httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await nextDelegate.Invoke(httpContext);
        }
Example #2
0
        public async Task <IActionResult> IsLoggedIn()
        {
            string accessToken  = HttpContext.Request.Cookies["accessToken"];
            string refreshToken = HttpContext.Request.Cookies["refreshToken"];

            if (accessToken != null && refreshToken != null)
            {
                var tokenHandler       = new JwtSecurityTokenHandler();
                JwtSecurityToken token = tokenHandler.ReadJwtToken(accessToken);
                var expDate            = token.ValidTo;

                var nameid      = token.Claims.Where(c => c.Type == "nameid").FirstOrDefault();
                var unique_name = token.Claims.Where(c => c.Type == "unique_name").FirstOrDefault();
                var email       = token.Claims.Where(c => c.Type == "email").FirstOrDefault();
                var role        = token.Claims.Where(c => c.Type == "role").FirstOrDefault();

                User identityUser = await userManager.FindByIdAsync(nameid.Value);

                if (expDate < DateTime.UtcNow)
                {
                    RefreshToken refresh = refreshTokenRepository.GetByUserIdAndToken(nameid.Value, refreshToken);

                    if (refresh != null)
                    {
                        if (refresh.ExpiryOn < DateTime.UtcNow || identityUser.IsLocked == true)
                        {
                            await refreshTokenRepository.Remove(refresh.Id);

                            // Set Token Cookie
                            var cookieOptions = new CookieOptions
                            {
                                HttpOnly = true,
                                Secure   = true,
                                SameSite = SameSiteMode.None,
                                Expires  = DateTime.UtcNow.AddDays(-1)
                            };
                            HttpContext.Response.Cookies.Append("accessToken", "", cookieOptions);
                            HttpContext.Response.Cookies.Append("refreshToken", "", cookieOptions);

                            return(Ok(new
                            {
                                Results = new { Code = "NotLoggedIn", Description = "Not Logged In Yet!" }
                            }));
                        }
                        else
                        {
                            var key = Encoding.UTF8.GetBytes(jwtBearerTokenSettings.SecretKey);
                            //var role = await userMgr.GetRolesAsync(identityUser);

                            var tokenDescriptor = new SecurityTokenDescriptor
                            {
                                Subject = new ClaimsIdentity(new Claim[]
                                {
                                    new Claim(ClaimTypes.NameIdentifier, nameid.Value),
                                    new Claim(ClaimTypes.Name, unique_name.Value),
                                    new Claim(ClaimTypes.Email, email.Value),
                                    new Claim(ClaimTypes.Role, role.Value)
                                }),

                                Expires            = DateTime.UtcNow.AddSeconds(jwtBearerTokenSettings.ExpiryTimeInSeconds),
                                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                                Audience           = jwtBearerTokenSettings.Audience,
                                Issuer             = jwtBearerTokenSettings.Issuer
                            };

                            // Set Access Token Cookie
                            var accessTokenCookieOptions = new CookieOptions
                            {
                                HttpOnly = true,
                                Secure   = true,
                                SameSite = SameSiteMode.None
                                           //Expires = DateTime.UtcNow.AddDays(7)
                            };
                            HttpContext.Response.Cookies.Append("accessToken", tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)), accessTokenCookieOptions);

                            return(Ok(new
                            {
                                Results = new
                                {
                                    Info = identityUser,
                                    Role = role
                                }
                            }));
                        }
                    }
                    else
                    {
                        return(BadRequest(new
                        {
                            Errors = new { Code = "ExpiredToken", Description = "Token expired!" }
                        }));
                    }
                }
                else
                {
                    return(Ok(new
                    {
                        Results = identityUser,
                        Role = role
                    }));
                }
            }

            return(BadRequest(new
            {
                Errors = new { Code = "ExpiredToken", Description = "Token expired!" }
            }));
        }