我正在尝试在核心webapi应用程序中使用JWT。这是我的Startup.ConfigureServices()
:
services.AddDbContextPool("Bla Bla");
services.AddIdentity<IdentityUser, IdentityRole>("Bla Bla");
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(o => {
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(c => {
c.RequireHttpsMetadata = false;
c.SaveToken = true;
c.TokenValidationParameters =
new TokenValidationParameters {
ValidIssuer = Configuration["JwtIssuer"],
ValidAudience = Configuration["JwtIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
ClockSkew = TimeSpan.Zero
};
});
services.AddRouting("Bla Bla");
services.AddMvcCore("Bla Bla").AddControllersAsServices();
这是Startup.Configure()
方法:
app.UseAuthentication();
app.UseMvc(rb =>
{ rb.MapRoute("api_default", "{controller}/{action}/{id?}"); });
无论如何,我已经创建了一个保护动作来进行测试(我期望返回一个HTTP 401 Unauthorized
错误):
public class AccountController : ControllerBase {
[HttpGet]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public async Task<object> Info() {
return "Authorized!";
}
}
但是它获得了授权并回应了“授权!”每时每刻。看来Authorize
属性根本没有作用。我想念什么吗?
P.S。我已经尝试了[Authorize]
和[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
属性。
P.S.2我尝试将控制器从ControllerBase
和Controller
扩展。
P.S.3我尝试不清除默认声明(已删除此行JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
)。
他们都没有工作。
框架和软件包信息:
netcoreapp2.1
Microsoft.AspNetCore
版本= 2.1.6
Microsoft.AspNetCore.Authentication.JwtBearer
版本= 2.1.2
Microsoft.AspNetCore.Identity.EntityFrameworkCore
版本= 2.1.6
Microsoft.AspNetCore.Mvc.Core
版本= 2.1.3
更新:
根据@sellotape's comment,我从操作中返回了User
对象:
[HttpGet]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public async Task<object> Info() {
return User;
}
这是输出JSON:
{
"identities": [
{
"isAuthenticated": false,
"claims": [],
"roleClaimType": "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"nameClaimType": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
}
],
"identity": {
"isAuthenticated": false,
"claims": [],
"roleClaimType": "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"nameClaimType": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
},
"claims": []
}
答案 0 :(得分:1)
主要问题是,当您使用.AddMvcCore()
时,您只使用了.AddMvc()
时获得的一小部分。对于许多解决方案,仅使用后者更为简单,因为您随后会自动添加以下内容并可以使用[source]:
如果您只想添加绝对需要的内容,则可以选择使用.AddMvcCore()
,但是随后您需要显式添加所需的MVC服务。例如在这种情况下(授权),您需要
services.AddMvcCore()
.AddAuthorization();
请注意,如何将.AddAuthorization()
应用于services.AddMvcCore()
的结果,IMvcBuilder
是services
,对于IServiceCollection
来说是 not class LineLimitException extends RuntimeException{
public LineLimitException(String message){
super(message);
}
}
。