【问题标题】:.NET Authentication user via cookie and not via header Bearer.NET 身份验证用户通过 cookie 而不是通过标头 Bearer
【发布时间】:2021-09-21 18:46:14
【问题描述】:

我正在寻找一种通过 JWT cookie 而不是通过授权标头对用户进行身份验证的方法。

我一直在四处寻找,但找不到我设法使用的答案。

目前我正在像这样进行身份验证:

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
         .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = key,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero
                };
                opt.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chat")))
                        {
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };
            });

什么等同于以相同的方式进行身份验证,但使用名为 JWT 的 cookie?

【问题讨论】:

  • 您好@אורי זבידה,我的回答是否帮助您解决了您的问题?如果是,请您接受作为答案吗?如果没有,请您跟进让我知道吗?参考:@987654321 @.谢谢。

标签: asp.net-core authentication cookies


【解决方案1】:

这是一个完整的工作演示,您可以关注:

生成令牌:

[Route("api/[Controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private IConfiguration _config;
    public ValuesController(IConfiguration config)
    {
        _config = config;
    }
    [Route("GenerateToken")]
    public async Task<IActionResult> GenerateToken()       
    {
         //add claims by yourself...
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Role, "Admin")
        };
        var token = new JwtSecurityToken(_config["Jwt:JwtIssuer"],
                                         _config["Jwt:JwtIssuer"],
                                         claims: claims,
                                         expires: DateTime.Now.AddDays(5),
                                         signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:JwtKey"])),
                                             SecurityAlgorithms.HmacSha256));
        var data = new JwtSecurityTokenHandler().WriteToken(token);

        HttpContext.Response.Cookies.Append("access_token", data, new CookieOptions { HttpOnly = true });
        
        return Ok(new { data });                   

    }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    var tokenValidationParameters = new TokenValidationParameters()
    {
        ValidIssuer = Configuration["Jwt:JwtIssuer"],
        ValidAudience = Configuration["Jwt:JwtIssuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:JwtKey"])),
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateIssuerSigningKey = true,
    };
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = tokenValidationParameters;
            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {                      
                    var token = context.HttpContext.Request.Cookies["access_token"];
                    if (!string.IsNullOrEmpty(token))
                    {
                        context.Token = token;
                        return Task.CompletedTask;
                    }
                    return Task.CompletedTask;
                }
            };
        });       
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //...           
    app.UseRouting();

    app.UseAuthentication();  //the middleware order must like here
    app.UseAuthorization();

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

appsettings.json:

{
  "jwt": {
    "JwtKey": "JWT_KEYsomethingyouwantwhichissecurewillworkk",
    "JwtIssuer": "https://xxxxxx.com",
    "JwtExpireDays": 15
  }
}

点击生成令牌方法后,您可以为令牌设置 cookie。然后就可以访问授权属性声明的方法了:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{  
    [Authorize]       //be sure add this...
    [HttpGet]
    public string Get()
    {
        return "Got in";
    }
}

结果:

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 2021-05-15
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    相关资源
    最近更新 更多