JWT Bearer ASP.Net Core 3.1 用户在服务器上为空

2024-03-15

今天,我一直在尝试使用 Microsoft.AspNetCore.Authentication.JwtBearer 库将 JSON Web 令牌信息绑定到 HttpContext.User。

问题: 每次调用服务器时,我都可以使用 [Authorize] 属性进入函数,但 User 对象完全是空白的。很高兴知道每个用户是谁。

My decoded JWT on the client-side: decoded_jwt

我的客户端函数调用服务器上的 [Authorize] C# 方法:

testAuth() {
    let token = localStorage.getItem("jwt");
    console.log(this.jwtHelper.decodeToken(token)); // Where I got the decoded JWT picture
    this.http.get(this.baseUrl + "Authentication/Test", {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
        "Authentication": "Bearer " + token
      })
    }).subscribe(response => {
      console.log(response); // never happens
    }, err => {
      console.log(err); // always happens because User.Identity is null
    });
  }

服务器方法中 User.Identity 始终为空,但我们可以通过 [Authorize] 属性:

[HttpGet]
[Authorize]
public IActionResult Test()
{
    // User.Identity is always blank, so a 500 error is thrown because Name == null
    return Ok(HttpContext.User.Identity.Name);
}

中间件管道:Startup.cs 中的ConfigureServices():

services.AddControllers();

            // Enable CORS (cross origin requests) so other sites can send requests to the auth API
            services.AddCors();

            // JWT
            // Use JSON Web Tokens for auth
            services.AddAuthentication(opt => {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = false,
                    IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration.GetValue<string>("JwtInfo:SecretKey"))),
                    ValidIssuer = Configuration.GetValue<string>("JwtInfo:ServerAddress", "http://localhost:44351/"), // Address that this project is running on
                    ValidAudience = Configuration.GetValue<string>("JwtInfo:ValidRecipients", "http://localhost:44364/") // Addresses of projects that are allowed to access this API
                };
            });

Startup.cs 中的配置():

app.UseHttpsRedirection();

            app.UseRouting();

            // Allow CORS (cross origin requests)
            // This must come before routing, authentication, and endpoints
            app.UseCors(option => option
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            // Use JWT authentication
            app.UseAuthentication();
            app.UseAuthorization();

如何正确地将 JWT 声明绑定到用户的声明?

如果用户为空,我如何通过[授权]?

感谢您的帮助!


包含令牌的标头设置不正确。 它应该是:

"Authorization": "Bearer " + token

而不是“身份验证”:“承载”+令牌

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JWT Bearer ASP.Net Core 3.1 用户在服务器上为空 的相关文章

随机推荐