简体   繁体   English

为什么ASP.NET中间件不验证令牌?

[英]Why isn't ASP.NET Middleware validating token?

I am trying to validate a JWT token being passed onto a C# application. 我正在尝试验证传递给C#应用程序的JWT令牌。 I confirmed that the token is being sent with every request. 我确认令牌随每个请求一起发送。 If I decode it manually everything works fine (I see the claims). 如果我手动对其进行解码,则一切正常(我看到了声明)。 However when I enable Authorization I get a 404 from the (Angular) client when I try to access the page. 但是,当我启用授权时,当我尝试访问页面时,会从(角度)客户端收到404。 My theory is that Angular is sending an OPTIONS request that is failing because it cant Auth with the token properly. 我的理论是Angular发送失败的OPTIONS请求,因为它无法正确使用令牌进行Auth。 Any advice on how to confirm this is the issue, and troubleshoot it? 关于如何确认这是问题的任何建议,并进行故障排除?

Auth via claim in token 通过令牌声明进行身份验证

[Authorize(Policy = "IsEmployee")]
[HttpGet("TestTokenAccess")]
public JsonResult TestTokenAccess()
{
    return Json("token decoded. you have claim IsEmployee=yes");
}

Manual token decode 手动令牌解码

[HttpGet("TestDecodeToken")]
public JsonResult TestDecodeToken()
{
    //https://shellmonger.com/2015/07/18/decoding-an-auth0-json-web-token-with-c/
    if (this.HttpContext.Request.Headers.ContainsKey("Authorization"))
    {
        var authHeader = this.HttpContext.Request.Headers["Authorization"];
        var authBits = authHeader.ToString().Split(' ');
        if (authBits.Length != 2)
        {
            return Json("{error:\"auth bits needs to be length 2\"}");
        }
        if (!authBits[0].ToLowerInvariant().Equals("bearer"))
        {
            return Json("{error:\"authBits[0] must be bearer\"}");
        }

        var secret = "xxxxx";

        //Install-Package JWT -Version 4.0.0
        try
        {
            var json = new JwtBuilder()
                .WithSecret(secret)
                //.MustVerifySignature()
                .Decode(authBits[1]);
            return Json(json);
        }
        catch (TokenExpiredException)
        {
            return Json("Token has expired");
        }
        catch (SignatureVerificationException)
        {
            return Json("Token has invalid signature");
        }
        catch (Exception e)
        {
            return Json($"other token err: {e.Message}");
        }

    }
    return Json("no token");
}

Startup.cs inside of ConfigureServices, but above the AddMVC() call Startup.cs ConfigureServices的内部,但高于AddMVC()调用

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = Configuration["JwtIssuer"];
        options.Audience = Configuration["JwtIssuer"];

        options.RequireHttpsMetadata = true;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["JwtIssuer"],
            ValidAudience = Configuration["JwtIssuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"]))
        };
    }
);

services.AddAuthorization(options =>
{
    options.AddPolicy("IsEmployee", policy => policy.Requirements.Add(new IsEmployeeRequirement("yes")));

});

services.AddSingleton<IAuthorizationHandler, IsEmployeeAuthorizationHandler>();

appsettings.json appsettings.json

  "JwtKey": "xxx",
  "JwtIssuer": "http://localhost:44362/",
  "JwtExpireDays": 30

snippet from web.config enable CORS 来自web.config的代码片段启用CORS

<!--added to enable CORS for Angular-->

<httpProtocol>

  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="https://localhost:44362/" />

    <add name="Access-Control-Allow-Headers" value="Content-Type" />

    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>

</httpProtocol>

Turned out my issue was an incorrectly specified claim in Startup.ConfigureServices() I needed to have: 原来我的问题是在Startup.ConfigureServices()指定的声明不正确,我需要:

services.AddAuthorization(options =>
{
    options.AddPolicy("IsEmployee", policy =>policy.RequireClaim("IsEmployee", "Yes", "yes"));          
});

rather than the policy specific way Microsoft used in their example here . 而不是Microsoft在此处示例中使用的特定于策略的方式。 I also removed the AddSingleton() line because it is not necessary 我也删除了AddSingleton()行,因为它没有必要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM