【问题标题】:how to logout the jwt token while click logout button click in c# using dotnet core如何在单击注销按钮时注销jwt令牌单击c#使用dotnet core
【发布时间】:2020-06-10 07:52:53
【问题描述】:

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();
            //});
        }

登录

  [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);
        }

以上代码我在 dotnet 核心应用程序中编写了一个基于 jwt 令牌的身份验证。我不知道单击注销按钮时如何销毁令牌。我是 dotnet 核心应用程序和 web api 的新手。

我参考了很多网站以强制注销 jwt 令牌,但我不知道如何销毁它。

【问题讨论】:

标签: c# .net-core jwt-auth webapi


【解决方案1】:

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

您还可以做的另一件事是将访问令牌的过期时间保持得很短。当用户注销并尝试刷新令牌时,它将失败。并且令牌会过期。但前提是您实现了刷新令牌机制。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    相关资源
    最近更新 更多