AuthorizeAttribute不会影响dotnet核心webapi 2.1应用程序中使用JWT的授权

时间:2018-11-25 08:29:42

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

我正在尝试在核心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我尝试将控制器从ControllerBaseController扩展。

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": []
}

1 个答案:

答案 0 :(得分:1)

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

  • API资源管理器
  • 授权
  • 观看次数
  • Razor View Engine
  • 剃刀纸页
  • JSON格式器
  • CORS
  • (还有其他几个人)

如果您只想添加绝对需要的内容,则可以选择使用.AddMvcCore(),但是随后您需要显式添加所需的MVC服务。例如在这种情况下(授权),您需要

services.AddMvcCore()
        .AddAuthorization();

请注意,如何将.AddAuthorization()应用于services.AddMvcCore()的结果,IMvcBuilderservices,对于IServiceCollection来说是 not class LineLimitException extends RuntimeException{ public LineLimitException(String message){ super(message); } }

相关问题