今天,我一直在尝试使用Microsoft.AspNetCore.Authentication.JwtBearer库将JSON Web令牌信息绑定到HttpContext.User。
问题:每次调用服务器时,我都可以使用[Authorize]属性进入函数,但是User对象完全为空。很高兴知道每个用户是谁。
我的客户端函数在服务器上调用[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中的Configure():
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声明绑定到用户的声明?
如果用户空白,我如何通过[授权]?
感谢您的帮助!
您需要使用IHttpContextAccessor并在configure services方法中注册依赖项。