代码之家  ›  专栏  ›  技术社区  ›  Rilcon42

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

  •  0
  • Rilcon42  · 技术社区  · 7 年前

    我正在尝试验证传递到C应用程序的JWT令牌。我确认每个请求都会发送令牌。如果我手动解码,一切正常(我看到声明)。但是,当我启用授权时,当我尝试访问页面时,我从(角度)客户端得到404。我的理论是Angular发送的OPTIONS请求失败,因为它不能正确地使用令牌进行身份验证。关于如何确认这是问题并排除故障有何建议?

    通过令牌中的声明进行身份验证

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

    [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");
    }
    

    启动.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>();
    

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

    web.config中的代码段

    <!--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>
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Rilcon42    7 年前

    原来我的问题是一个错误的指定索赔 Startup.ConfigureServices() 我需要:

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

    而不是微软在他们的例子中使用的特定于策略的方式 here AddSingleton() 因为这不是必须的