0

Startup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<AppDbContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDBConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<AppDbContext>();

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            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"])),
            };
        });

        services.AddMvc();
        services.AddControllers(options => options.EnableEndpointRouting = false);
        services.AddScoped<IEmployeeRepository, SQLEmployeeRepository>();
    }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                       name: "default",
                       template: "{controller=Default}/{action=index}");
            });

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllers();
            //});
        }

Login

  [HttpPost]
    [Route("login"), AllowAnonymous]
    public IActionResult Login([FromBody]UserModel login) //
    {
        IActionResult response = Unauthorized();
        var user = AuthenticateUser(login);

        if (user != null)
        {
            var tokenString = GenerateJSONWebToken(user);
            var handler = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(tokenString);
            var tokenS = handler.ReadToken(tokenString) as JwtSecurityToken;

            var id = tokenS.Claims.First(claim => claim.Type == "email").Value;

            response = Ok(new
            {
                token = tokenString,
            });
        }

        return response;
    }


private Users AuthenticateUser(UserModel login)
        {
            Users user = context.Users.FirstOrDefault(x => x.Email == login.UserName && x.Password == login.Password);
            return user;
        }

        private string GenerateJSONWebToken(Users userInfo)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, userInfo.Email),
                new Claim(JwtRegisteredClaimNames.Email, userInfo.Email),
                //new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
              _config["Jwt:Issuer"],
              claims,
              expires: DateTime.Now.AddMinutes(120),
              signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

Above code I wrote a jwt token based authentication in dotnet core application. I don't know How to destroy the token when logout button click. I am new to dotnet core application and web api.

I am refer so many websites for logout forcefully destroy the jwt token but I didn't get how to destroy it.

Saidulu S
  • 25
  • 6
  • This might help: [invalidating-json-web-tokens](https://stackoverflow.com/questions/21978658/invalidating-json-web-tokens) – Kush Feb 26 '20 at 12:33

1 Answers1

-1

The thing with access tokens is that it is not possible to invalidate from the server. What you can do is generate a session and link the access token to some identifier. Once the user logs out, invalidate the session. Now next time when you receive the access token, you must compare that id and verify. You can store the identifier in the claims.

One more thing you can do is to keep the access token expiration very short. When a user logs out, and user tries to refresh the token, it would fail. And the token would have expired. But this is provided you have a refresh token mechanism implemented.

You can also try deleting the access token from the client as soon as logout is initiated.

Shahzad
  • 1,677
  • 1
  • 12
  • 25