我实现401时实现AddJwtBearer并在dotnet Core 2中的OnMessageReceived(ctx)上标记成功

时间:2019-04-10 22:03:10

标签: oauth .net-core jwt jwt-auth

这是Startup.cs的代码:

var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Auth0MachineToMachineSecret);

services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.Events = new JwtBearerEvents
    {
        OnTokenValidated = (ctx) =>
        {
            return Task.CompletedTask;
        },
        OnMessageReceived = (ctx) =>
        {
            string token = ctx.Request.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);
            IDictionary<string, object> headers = AuthenticationHelper.JwtHeaders(token);
            ctx.Token = ctx.Request.Headers["Authorization"].ToString();

            // Validate the HS256 Key using a PSK
            if (headers.ContainsKey("alg") && headers["alg"].ToString() == "HS256")
            {
                string secret = appSettings.Auth0MachineToMachineSecret;
                string payload = AuthenticationHelper.JwtDecode(token, secret);
                ctx.Principal = this.SetTokenInfo(JObject.Parse(payload), appSettings.Auth0AppMeta, ctx);
            }

            // Validate token with a public RSA key published by the IDP as a list of JSON Web Keys (JWK)
            // step 0: you've read the keys from the jwks_uri URL found in http://<IDP authority URL>/.well-known/openid-configuration endpoint
            if (headers.ContainsKey("alg") && headers["alg"].ToString() == "RS256")
            {
                IDPKey iDpKey = AuthenticationHelper.FindIdpKey(headers, "kid", AuthenticationHelper.GetIdpKeys(appSettings.Auth0Tenant));

                if (iDpKey == null)
                {
                    return Task.CompletedTask;
                }

                //If everything is good set the Authorization as true and the CRM user.
                JObject payload = AuthenticationHelper.ParsePayload(token);
                ctx.Principal = this.SetTokenInfo(payload, appSettings.Auth0AppMeta, ctx);
            }

            ctx.Token = token;

            ctx.Success();

            return Task.CompletedTask;
        }
    };
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
});

// configure DI for application services
services.AddScoped<IUserService, UserService>();

即使我知道我提供的JWT代码正确(已通过jwt.io验证),我的控制器也始终在端点返回401:

[AllowAnonymous]
[HttpGet("all")]
public IActionResult GetAll()
{
    var users =  _userService.GetAll();
    return Ok(users);
}

重要的是要知道我不是oAuth提供者...它是auth0,但所有这些都在配置中,而我的使用纯粹是确保用户被授权使用我的Web api 2.2核心Web api结束点。

OnMessageReceived启动,我用它设置我的委托人并将其标记为成功(否则它将始终转到OnAuthenticationFailed),然后即使在jwt中验证了Bearer代码,我在Fiddler中也得到401的响应。 io。

任何帮助将不胜感激。

0 个答案:

没有答案