如何在单击注销按钮的同时注销jwt令牌使用dotnet core在c#中单击

如何在单击注销按钮的同时注销jwt令牌使用dotnet core在c#中单击,c#,.net-core,jwt-auth,webapi,C#,.net Core,Jwt Auth,Webapi,Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddDbContextPool<AppDbContext>( options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDBConnection"))); s

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();
            //});
        }
在上面的代码中,我在dotnet核心应用程序中编写了一个基于jwt令牌的身份验证。我不知道如何在单击注销按钮时销毁令牌。我不熟悉dotnet核心应用程序和web api


我是指这么多的网站注销强制销毁jwt令牌,但我不知道如何销毁它

访问令牌的问题是不可能从服务器上失效。您可以做的是生成一个会话并将访问令牌链接到某个标识符。用户注销后,使会话无效。现在,下次当您收到访问令牌时,必须比较该id并进行验证。您可以将标识符存储在声明中

您可以做的另一件事是使访问令牌的过期时间非常短。当用户注销,并且用户尝试刷新令牌时,它将失败。而且代币可能已经过期了。但前提是您实现了刷新令牌机制

您还可以尝试在注销启动后立即从客户端删除访问令牌。

这可能会有帮助:
  [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);
        }