【问题标题】:The AuthorizeAttribute doesn't effect authorization using JWT in dotnet core webapi 2.1 applicationAuthorizeAttribute 不影响在 dotnet core webapi 2.1 应用程序中使用 JWT 的授权
【发布时间】:2019-04-27 04:42:31
【问题描述】:

我正在尝试在核心 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 属性根本不起作用。我错过了什么吗?

附: [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,我已经从action中返回了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": []
}

【问题讨论】:

  • 在该控制器操作中放置一个断点并检查用户声明和身份以查看经过身份验证的身份来自何处。这应该会提供一些线索...
  • @sellotape 没什么重要的。声明和身份是空的。查看更新以查看完整的 User 对象。
  • 我认为您在ConfigureServices() 中缺少services.AddAuthorization();...
  • @sellotape 我添加了services.AddAuthorization() 但没有任何改变):
  • 谢谢;我现在已经添加了答案。

标签: c# authorization jwt asp.net-core-webapi netcoreapp2.1


【解决方案1】:

主要问题是,当您使用.AddMvcCore() 时,您只连接了使用.AddMvc() 时获得的一小部分。对于许多解决方案,只使用后者更简单,因为您会自动添加以下内容并准备使用 [source]:

  • API 浏览器
  • 授权
  • 观看次数
  • Razor 视图引擎
  • 剃刀页面
  • JSON 格式化程序
  • CORS
  • (其他几个)

如果您希望只添加您绝对需要的内容,您可以选择使用.AddMvcCore(),但是您需要明确添加您需要的 MVC 服务;例如在这种情况下(授权),您需要

services.AddMvcCore()
        .AddAuthorization();

注意这里的.AddAuthorization() 是如何应用于services.AddMvcCore() 的结果,这是一个IMvcBuilder,不是 到services,这是一个IServiceCollection。

【讨论】:

    猜你喜欢
    • 2020-02-12
    • 2020-07-21
    • 1970-01-01
    • 2019-03-18
    • 2018-12-20
    • 2019-09-29
    • 1970-01-01
    • 2018-09-07
    • 2016-12-11
    相关资源
    最近更新 更多