UseJwtBearerAuthentication需要哪些TokenValidationParameters

时间:2017-02-09 21:21:45

标签: asp.net-web-api token owin jwt okta

我想在我的.net JwtBearerAuthentication上做WebAPI,但它无法正常工作。 Authorize属性始终声明isAuthorized = false。

我正在与Okta一起担任SSO。我在客户端进行身份验证并获取访问令牌和ID令牌。在webapi get请求中,我在authorize标头中提供了访问令牌(我也尝试了id标记),并且我能够在webapi actioncontext中看到带有令牌的授权标头。

在我的startup.cs中,我有以下

var clientID = WebConfigurationManager.AppSettings["okta:ClientId"];

var oidcIssuer = WebConfigurationManager.AppSettings["okta:OIDC_Issuer"];

TokenValidationParameters tvps = new TokenValidationParameters
{
    ValidAudience = clientID,
    ValidateAudience = true,
    ValidIssuer = oidcIssuer,
    ValidateIssuer = true  
};

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    TokenValidationParameters = tvps,
    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
    {
        new OpenIdConnectCachingSecurityTokenProvider(oidcIssuer + "/.well-known/openid-configuration")
    }
});

我错过了一些我需要的TokenValidationParameters吗?

2 个答案:

答案 0 :(得分:1)

我的问题不在于选项。 这是100%需要移动

app.UseWebApi(config);

低于所有owin设置的东西。

答案 1 :(得分:0)

当我打字时,我看到twaldron能够弄明白了!

我也意识到他在询问WebAPI,而不是MVC。但是,以下是我需要使用ASP.NET Core MVC进行以下操作的代码,特别感兴趣的可能是这一行,这对于访问JWT中的其他声明是必要的:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

以下是此代码示例如何在命令行中运行,$ID_TOKEN变量包含有效的JWT:

$ curl -H "Authorization: Bearer ${ID_TOKEN}" http://localhost:3000/test/test
sub: 01a23b4cd5eFgHI6j7k8 email:test@example.com

<强> Setup.cs

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;

namespace WebApplication
{
    public class Startup
    {
        readonly string clientId = string.Empty;
        readonly string issuer = string.Empty;
        readonly string audience = string.Empty;

        public Startup(IHostingEnvironment env)
        {
            clientId = "A0b1CDef2GHIj3k4lm5n";
            issuer = "https://example.okta.com";
            audience = "A0b1CDef2GHIj3k4lm5n";
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddDebug();

            // https://github.com/aspnet/Security/issues/1043#issuecomment-261937401
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            TokenValidationParameters tvps = new TokenValidationParameters
            {

                ValidateAudience = true,
                ValidAudience = audience,

                ValidateIssuer = true,
                ValidIssuer = issuer,

                ValidateLifetime = true,
                ClockSkew = TimeSpan.FromMinutes(5)
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                MetadataAddress = issuer + "/.well-known/openid-configuration",
                TokenValidationParameters = tvps
            });


            app.UseStaticFiles();

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

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

Controllers / Test.cs

    [Authorize]
    public IActionResult Test()
    {
        var contextUser = User.Identity as ClaimsIdentity;
        Dictionary<string, string> claim = contextUser.Claims.ToDictionary(x => x.Type, x => x.Value);

        var output = "sub: " + claim["sub"] + " email:" + claim["email"];
        return Content(output);
    }