使用ASP.Net 5和ASP.NET MVC 6进行JwtBearerAuthentication

时间:2015-12-17 21:47:26

标签: asp.net-core asp.net-core-mvc

我试图让JwtBearerAuthentication在ASP.Net 5,MVC6 WebApi应用程序中运行。我在令牌端点生成了Jwt令牌,但是当我尝试使用令牌访问所有WebApi端点时,我收到以下错误:

System.InvalidOperationException:IDX10803:无法获取配置  来自:localhost:5000 / .well-known / openid-configuration。

这是我的Startup.cs中的代码,任何人都可以告诉我我做错了什么。

public Startup(IHostingEnvironment env)
{
    const string _TokenIssuer = "http://localhost:5000/";
    const string _TokenAudience = "http://localhost:5000/";

public void ConfigureServices(IServiceCollection services)
    {
    ...
        RsaSecurityKey _signingKey = null;
        SigningCredentials signingCredentials = null;
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
        {
            signingKey = new RsaSecurityKey(rsa.ExportParameters(true));
            signingCredentials = new SigningCredentials(_SigningKey, SecurityAlgorithms.RsaSha256Signature);
        }
        services.AddInstance<SigningCredentials>(signingCredentials);  // tobe used in JwtTokenHandler in the Token Controller

    var jwtOptions = new JwtBearerOptions();
        jwtOptions.AutomaticAuthenticate = true;
        jwtOptions.TokenValidationParameters.IssuerSigningKey = signingKey;
        jwtOptions.TokenValidationParameters.ValidAudience = _TokenAudience;
        jwtOptions.TokenValidationParameters.ValidIssuer = _TokenIssuer;
        services.AddInstance<JwtBearerOptions>(jwtOptions);   //tobe used in the Token Controller

        services.AddAuthorization(auth =>
        {
            auth.AddPolicy(JwtBearerDefaults.AuthenticationScheme, new AuthorizationPolicyBuilder()
                .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                .RequireAuthenticatedUser().Build());
        });

        services.AddMvc();
        services.AddAuthentication();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ...
        //Add Bearer Authentication Middleware, make sure this is before UseIdentity line
        app.UseJwtBearerAuthentication(options =>
        {
            options.AutomaticAuthenticate = true;
            options.Audience = _TokenAudience;
            options.Authority = _TokenIssuer;
            options.RequireHttpsMetadata = false;
        });

        app.UseIdentity();
        app.UseMvc();
    }
}

我使用Kestrel托管,我的服务网址为http://localhost:5000/XXX

编辑:我仍然遇到JwtBearerAuthentication验证令牌的问题。我切换到使用OpenIdConnectServer来发出令牌。那部分没问题。但是当尝试使用JwtBearerAuthentication验证令牌时,除非我设置options.TokenValidationParameters.ValidateAudience = false;我总是得到SecurityTokenInvalidAudienceException: IDX10208: Unable to validate audience. validationParameters.ValidAudience is null or whitespace and validationParameters.ValidAudiences is null

当我将其设置为false时,我可以点击我的WebApi代码,但是,当我检查控制器中的User对象时,User.Identity.Name未设置。 User.Identity.Authenticationtype="Authentication.Federation"User.Identity.IsAuthenticated = true。我可以看到身份下的声明列表,但并非我添加到令牌的所有声明都在那里。这与我在.Net 4.5中使用UseOAuthBearerAuthentication看到的完全不同。

我已将我的测试项目放在GitHub https://github.com/Sally-Xu/Net5Start中。你能看出什么问题吗?

1 个答案:

答案 0 :(得分:3)

您看到的错误是由于您将Authority设置为非空值而引起的。仅当您的令牌由AspNet.Security.OpenIdConnect.Server等OpenID Connect服务器颁发时,才应使用此属性。由于您使用的是自定义令牌控制器,因此我认为它不是真正的OAuth2 / OpenID Connect服务器,这解释了您看到此错误的原因。

停止设置此属性,它应该可以工作。请注意,您必须直接在IssuerSigningKey来电as it won't reuse the options set from ConfigureServices中设置UseJwtBearerAuthentication