AspNetCore.Authentication.JwtBearer失败,没有可用于使用.NET的核心RC2令牌SecurityTokenValidator [英] AspNetCore.Authentication.JwtBearer fails with No SecurityTokenValidator available for token with .net core RC2

查看:4571
本文介绍了AspNetCore.Authentication.JwtBearer失败,没有可用于使用.NET的核心RC2令牌SecurityTokenValidator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图得到一个简单的终端工作的问题和消耗JWT令牌使用AspNew.Security.OpenIdConnect.Server发出令牌,并使用Microsoft.AspNetCore.Authentication.JwtBearer验证。

I'm trying to get a simple endpoint working that issues and consumes JWT tokens using AspNew.Security.OpenIdConnect.Server to issue the token and validating using Microsoft.AspNetCore.Authentication.JwtBearer.

我可以生成令牌不错,但尝试进行身份验证令牌失败,错误承载未通过身份验证。失败消息:没有可用的令牌SecurityTokenValidator:{令牌}

I can generate the token fine but trying to authenticate the token fails with the error Bearer was not authenticated. Failure message: No SecurityTokenValidator available for token: {token}

在这一点上我已经剥离出来的一切,并有以下几点:

At this point I've stripped everything out and have the following:

project.json

project.json

{
  "dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
    "AspNet.Security.OAuth.Validation": "1.0.0-alpha1-final",
    "AspNet.Security.OpenIdConnect.Server": "1.0.0-beta5-final",
    "Microsoft.AspNetCore.Authentication": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0-rc2-final"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    }
  },

  "frameworks": {
    "net461": { }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Startup.cs方式:

Startup.cs methods:

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthorization(options =>
                {
                    options.AddPolicy(JwtBearerDefaults.AuthenticationScheme,
                        builder =>
                        {
                            builder.
                            AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).
                            RequireAuthenticatedUser().
                            Build();
                        }
                    );
                }
            );

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

        // 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)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            var jwtOptions = new JwtBearerOptions()
            {
                AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
                AutomaticAuthenticate = true,
                Authority = "http://localhost:5000/",
                Audience = "http://localhost:5000/",
                RequireHttpsMetadata = false
            };

            jwtOptions.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>
                (
                    metadataAddress: jwtOptions.Authority + ".well-known/openid-configuration",
                    configRetriever: new OpenIdConnectConfigurationRetriever(),
                    docRetriever: new HttpDocumentRetriever { RequireHttps = false }
                );


            app.UseJwtBearerAuthentication(jwtOptions);

            app.UseOpenIdConnectServer(options =>
            {
                options.AllowInsecureHttp = true;
                options.AuthorizationEndpointPath = Microsoft.AspNetCore.Http.PathString.Empty;
                options.Provider = new OpenIdConnectServerProvider
                {
                    OnValidateTokenRequest = context =>
                    {
                        context.Skip();
                        return Task.FromResult(0);
                    },

                    OnGrantResourceOwnerCredentials = context =>
                    {
                        var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
                        identity.AddClaim(ClaimTypes.NameIdentifier, "[unique id]");

                        identity.AddClaim("urn:customclaim", "value", OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken);

                        var ticket = new AuthenticationTicket(
                            new ClaimsPrincipal(identity),
                            new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties(),
                            context.Options.AuthenticationScheme);

                        ticket.SetScopes("profile", "offline_access");

                        context.Validate(ticket);

                        return Task.FromResult(0);
                    }
                };
            });            

            app.UseMvc();
        }

发送的X URL-CN codeD POST到的http://本地主机:5000 与grant_type =密码,用户名= foo,那么密码=杆产生预期的access_token。

sending x-url-encoded POST to http://localhost:5000 with grant_type=password, username=foo, password=bar generates the expected access_token.

我已经添加了 [授权(载体)] 属性的Values​​Controller,这是按预期在JwtBearerMiddlewear被调用,但我无法得到令牌验证。

I've added the [Authorize("Bearer")] attribute to the ValuesController and this is working as expected in the JwtBearerMiddlewear is invoked but I am unable to get the token to validate.

有没有人有这方面的工作与.NET的核心RC2?我已经有了RC1工作同样的事情,但一直未能得到这个下去。

Has anyone got this working with .net core RC2? I've got the same thing working on RC1 but have been unable to get this going.

感谢。

推荐答案

与beta5的(对于ASP.NET核心RC2)开始,的中的OpenID Connect服务器中间件不再使用JWT作为默认格式访问令牌的。相反,它使用不透明的令牌,由坚如磐石的ASP.NET核心数据保护栈(酷似身份验证Cookie)进行加密。

Starting with beta5 (for ASP.NET Core RC2), the OpenID Connect server middleware no longer uses JWT as the default format for access tokens. Instead, it uses opaque tokens, encrypted by the rock-solid ASP.NET Core Data Protection stack (exactly like authentication cookies).

您有3种选择来解决您看到的错误:

You have 3 options to fix the error you're seeing:


  • 使用<一个href=\"https://github.com/aspnet-contrib/AspNet.Security.OAuth.Extensions/tree/dev/src/AspNet.Security.OAuth.Validation\"相对=nofollow> 开发,以支持不透明令牌新的OAuth2验证的中间件(推荐的选项后,如果你的API和授权服务器是同一应用程序的一部分)。对于这一点,让你有 AspNet.Security.OAuth.Validation 引用 project.json 和替换 app.UseJwtBearerAuthentication(...) app.UseOAuthValidation()。您还可以删除 Microsoft.AspNetCore.Authentication.JwtBearer project.json

  • Use the new OAuth2 validation middleware developed to support opaque tokens (the recommended option, if your API and your authorization server are part of the same app). For that, keep the AspNet.Security.OAuth.Validation reference you have in project.json and replace app.UseJwtBearerAuthentication(...) by just app.UseOAuthValidation(). You can also remove Microsoft.AspNetCore.Authentication.JwtBearer from project.json.

  • 强制的OpenID Connect服务器中间件通过调用 options.UseJwtTokens()的选项来使用JWT令牌。请注意,您还必须调用 ticket.SetResources(...)附加与JWT令牌适当的观众(见本其他的SO发布获得更多信息)。

  • Force the OpenID Connect server middleware to use JWT tokens by calling options.UseJwtTokens() in the options. Note that you'll also have to call ticket.SetResources(...) to attach the appropriate audience with the JWT tokens (see this other SO post for more information).

  • 使用<一个href=\"https://github.com/aspnet-contrib/AspNet.Security.OAuth.Extensions/tree/dev/src/AspNet.Security.OAuth.Introspection\"相对=nofollow>新反省中间件。这个选项是比较复杂,需要实施 ValidateIntrospectionRequest 事件来验证客户端凭据。只有当你知道你在做什么使用它。

  • Use the new introspection middleware. This option is more complex and requires implementing the ValidateIntrospectionRequest event to validate the client credentials. Only use it if you know what you're doing.

这篇关于AspNetCore.Authentication.JwtBearer失败,没有可用于使用.NET的核心RC2令牌SecurityTokenValidator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆