.Net核心JWT身份验证与自定义API密钥中间件

Jam*_*ees 6 .net c# jwt asp.net-identity asp.net-core

我有一个.Net Core 2.0应用程序,它使用JWT令牌来授权用户.这一切都很好,但我希望有一些API密钥机制,以允许其他应用程序集成,但我似乎无法使用当前的身份验证.

码:

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
            IMemoryCache cache, IServiceProvider serviceProvider)
{
    app.UseAuthentication();

    ApiKeyMiddlewear(app, serviceProvider);

    app.UseMvc(routes =>
    { 
        routes.MapRoute(
               name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }
}


    private static void ApiKeyMiddlewear(IApplicationBuilder app, IServiceProvider serviceProvider)
    {
        app.Use(async (context, next) =>
        {
            if (context.Request.Path.StartsWithSegments(new PathString("/api")))
            {
                // Let's check if this is an API Call
                if (context.Request.Headers["ApiKey"].Any())
                {
                    // validate the supplied API key
                    // Validate it
                    var headerKey = context.Request.Headers["ApiKey"].FirstOrDefault();
                    var settingsProvider = serviceProvider.GetService<ISettingsService<OmbiSettings>>();
                    var ombiSettings = settingsProvider.GetSettings();
                    var valid = ombiSettings.ApiKey.Equals(headerKey, StringComparison.CurrentCultureIgnoreCase);
                    if (!valid)
                    {
                        context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                        await context.Response.WriteAsync("Invalid API Key");
                    }
                    else
                    {
                        var identity = new GenericIdentity("API");
                        identity.AddClaim(new System.Security.Claims.Claim("Origin", "Api"));
                        identity.AddClaim(new System.Security.Claims.Claim("role", "Admin"));

                        var principal = new GenericPrincipal(identity, new[] {"ApiUser"});
                        context.User = principal;
                        await next();
                    }
                }
                else
                {
                    await next();
                }
            }
            else
            {
                await next();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,在上面的代码中,您可以看到我正在拦截提供名为ApiKey的标头的HTTP请求,然后将其验证为我存储的内容.这部分都可以工作,但是当使用Authorize属性调用API方法时,这不起作用,我得到以下错误日志:

2017-09-19 08:15:17.280 +01:00 [Information] Request starting HTTP/1.1 POST http://localhost:52038/api/v1/Identity/ application/json 372
2017-09-19 08:15:21.967 +01:00 [Information] Authorization failed for user: "API".
2017-09-19 08:15:21.976 +01:00 [Information] Authorization failed for the request at filter '"Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter"'.
2017-09-19 08:15:21.981 +01:00 [Information] Executing ForbidResult with authentication schemes ([]).
2017-09-19 08:15:21.991 +01:00 [Information] AuthenticationScheme: "Bearer" was forbidden.
2017-09-19 08:15:21.996 +01:00 [Information] Executed action "Ombi.Controllers.IdentityController.CreateUser (Ombi)" in 38.8268ms
2017-09-19 08:15:22.004 +01:00 [Information] Request finished in 4723.032ms 403 
Run Code Online (Sandbox Code Playgroud)

现在我猜这是与请求仅提供ApiKey标头而不是Authorization具有正确JWT标记的标头.

我怎么能只提供一个ApiKey标头,当没有ApiKey标头然后回退到需要一个JWT标记?

Ara*_*yan 7

申请Claim("role", "Admin")GenericPrincipal不会GenericPrincipal有任何影响,因为与角色声明无关。因此,如果要将 admin 角色应用于GenericPrincipal,则需要将其添加到构造函数参数中:

 var principal = new GenericPrincipal(identity, new[] {"Admin","ApiUser"});
 context.User = principal;
Run Code Online (Sandbox Code Playgroud)