.NET Core JWTBearerAuth 返回 "Unauthorized"
.NET Core JWTBearerAuth returning "Unauthorized"
我正在尝试将身份验证添加到我的 .NET Core 3.1 应用程序,但是每次尝试使用返回的 JWT 都会导致 401 Unauthorized
。我已经完成了几个调试步骤:
- 我已使用 this online validator.
确认我的 authenticate
端点 returns 的 JWT 有效
- 我已经重新订购了我的
UseRouting()
、UseAuthentication()
、UseAuthorization()
和 UseEndpoints()
。
- 我暂时完全禁用了
audience
和 issuer
验证。
有人可以找出我哪里出错了,或者至少提供一些正确调试的方法,以便我可以找到问题所在吗?谢谢。下面的代码。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
var key = Encoding.UTF8.GetBytes("thisismycustomSecretkeyforauthentication");
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "issuer",
ValidAudience = "audience",
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
services
.AddControllers();
.AddMvc(options => { options.EnableEndpointRouting = false; });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app
.UseStaticFiles()
.UseHsts()
.UseHttpsRedirection()
.UseMvc(routes => routes.MapRoute(name: "default", template: "{controller=App}/{action=Index}/{id?}"))
.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(endpoints => { endpoints.MapControllers(); });
if (env.IsDevelopment())
app.UseSpa(spa => spa.UseProxyToSpaDevelopmentServer("https://localhost:22010"));
}
AuthController.cs
[ApiController]
[Authorize]
[Route("[controller]")]
public class AuthController : Controller
{
[AllowAnonymous]
[HttpPost("authenticate")]
public async Task<IActionResult> Authenticate(AuthenticationRequest request)
{
if (request.Username != "test" || request.Password != "admin")
return Unauthorized();
var tokenHandler = new JwtSecurityTokenHandler();
var tokenKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("thisismycustomSecretkeyforauthentication"));
var token = new JwtSecurityToken
(
issuer: null,
audience: null,
claims: new Claim[] { new Claim(ClaimTypes.Name, request.Username) },
expires: DateTime.Now.AddDays(30),
signingCredentials: new SigningCredentials(tokenKey, SecurityAlgorithms.HmacSha256)
);
var tokenResponse = tokenHandler.WriteToken(token);
return Ok(tokenResponse);
}
[HttpGet]
public IActionResult Do()
{
return Ok("Done!");
}
}
身份验证设置看起来不错,您的中间件顺序符合 Microsoft Documentation。
根据提供的代码,您似乎缺少实际的授权选项。这类似于 .
问题
我正在尝试将身份验证添加到我的 .NET Core 3.1 应用程序,但是每次尝试使用返回的 JWT 都会导致 401 Unauthorized
。我已经完成了几个调试步骤:
- 我已使用 this online validator. 确认我的
- 我已经重新订购了我的
UseRouting()
、UseAuthentication()
、UseAuthorization()
和UseEndpoints()
。 - 我暂时完全禁用了
audience
和issuer
验证。
authenticate
端点 returns 的 JWT 有效
有人可以找出我哪里出错了,或者至少提供一些正确调试的方法,以便我可以找到问题所在吗?谢谢。下面的代码。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
var key = Encoding.UTF8.GetBytes("thisismycustomSecretkeyforauthentication");
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "issuer",
ValidAudience = "audience",
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
services
.AddControllers();
.AddMvc(options => { options.EnableEndpointRouting = false; });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app
.UseStaticFiles()
.UseHsts()
.UseHttpsRedirection()
.UseMvc(routes => routes.MapRoute(name: "default", template: "{controller=App}/{action=Index}/{id?}"))
.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(endpoints => { endpoints.MapControllers(); });
if (env.IsDevelopment())
app.UseSpa(spa => spa.UseProxyToSpaDevelopmentServer("https://localhost:22010"));
}
AuthController.cs
[ApiController]
[Authorize]
[Route("[controller]")]
public class AuthController : Controller
{
[AllowAnonymous]
[HttpPost("authenticate")]
public async Task<IActionResult> Authenticate(AuthenticationRequest request)
{
if (request.Username != "test" || request.Password != "admin")
return Unauthorized();
var tokenHandler = new JwtSecurityTokenHandler();
var tokenKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("thisismycustomSecretkeyforauthentication"));
var token = new JwtSecurityToken
(
issuer: null,
audience: null,
claims: new Claim[] { new Claim(ClaimTypes.Name, request.Username) },
expires: DateTime.Now.AddDays(30),
signingCredentials: new SigningCredentials(tokenKey, SecurityAlgorithms.HmacSha256)
);
var tokenResponse = tokenHandler.WriteToken(token);
return Ok(tokenResponse);
}
[HttpGet]
public IActionResult Do()
{
return Ok("Done!");
}
}
身份验证设置看起来不错,您的中间件顺序符合 Microsoft Documentation。
根据提供的代码,您似乎缺少实际的授权选项。这类似于