.net core implements JWT Token with Razor pages | Plus solve early logout issue

Problem: If we use claims with cookies authentication, when we host to shared hosting or some other side then its IIS server log out earlier while we applied session time out or idle time out

Secondly, we will learn how to use JWT Token with Razor pages, so both things will be achieved with this article.

  1. Step: put this code on your appsettings.json file.
 "Jwt": {
    "Key": "ThisismySecretKey",
    "Issuer": "www.soninfosys.com",
    "Audience": "http://localhost:52527/",
    "ExpireMinutes": "20000"
  }

2. Step: put code on yourproject.csproj file

<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.1" />

3. Step: put below code on Startup.cs and method- public void ConfigureServices(IServiceCollection services)

              services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new
                    SymmetricSecurityKey
                    (Encoding.UTF8.GetBytes
                    (Configuration["Jwt:Key"]))
                };
            });

4. Step: after authentication of login writes this code.

var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.Role, user.RoleName), 
                     
                };

var token = BuildToken(configuration["Jwt:Key"], configuration["Jwt:Issuer"], claims, configuration["Jwt:ExpireMinutes"].ToInt32());

            CookieOptions option = new CookieOptions();
            option.Expires = DateTime.Now.AddMinutes(configuration["Jwt:ExpireMinutes"].ToInt32());
            httpContext.Response.Cookies.Append("Token", token, option);

5. Step: in the same login file or another helper file write these methods.

        public static string BuildToken(string key, string issuer, List<Claim> claims, int expireMinutes)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            var tokenDescriptor = new JwtSecurityToken(issuer, issuer, claims,
                expires: DateTime.Now.AddMinutes(expireMinutes), signingCredentials: credentials);
            return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
        }

        public static bool IsTokenValid(string key, string issuer, string token)
        {
            var mySecret = Encoding.UTF8.GetBytes(key);
            var mySecurityKey = new SymmetricSecurityKey(mySecret);
            var tokenHandler = new JwtSecurityTokenHandler();
            try
            {
                tokenHandler.ValidateToken(token,
                new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidIssuer = issuer,
                    ValidAudience = issuer,
                    IssuerSigningKey = mySecurityKey,
                }, out SecurityToken validatedToken);
            }
            catch
            {
                return false;
            }
            return true;
        }

6. Step: above your authorized controllers must use this.

    [MyAuth]
    public class HomeController : Controller
    {

7. Step: Create [MyAuth] IActionFilter

public class MyAuth : Attribute, IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {


            var _config = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
            var token = context.HttpContext.Request.Cookies["Token"];
            if (!Auths.IsTokenValid(_config["Jwt:Key"].ToString(),
                _config["Jwt:Issuer"].ToString(), token))
            {
                context.Result = new RedirectResult("/auth/login?returnUrl=" + context.HttpContext.Request.Path.ToString());
            }
         

        }

        public void OnActionExecuted(ActionExecutedContext context)
        {

        }


    }

8. Step: on logout method must do this to delete cookie

Response.Cookies.Delete("Token");

9. Step: it’s for hosting settings if you wanted to do for stay login as per you wanted.

asp.net settings

IIS application pool settings.