简体   繁体   中英

how to logout the jwt token while click logout button click in c# using dotnet core

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM