AspNetCore.Authentication.JwtBearer失败,没有SecurityTokenValidator可用于.net核心RC2的令牌

前端之家收集整理的这篇文章主要介绍了AspNetCore.Authentication.JwtBearer失败,没有SecurityTokenValidator可用于.net核心RC2的令牌前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图让一个简单的端点工作,问题和消耗JWT令牌使用AspNew.Security.OpenIdConnect.Server发出令牌和验证使用Microsoft.AspNetCore.Authentication.JwtBearer.

我可以生成令牌,但尝试验证令牌失败,错误承载未通过身份验证.失败消息:No SecurityTokenValidator可用于令牌:{token}

在这一点上,我已经把所有东西都删除了,并且具有以下几点:

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方法

// 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编码POST到http://localhost:5000与grant_type = password,username = foo,password = bar生成预期的access_token.

我已经将[Authorize(“Bearer”)]属性添加到ValuesController中,并且在JwtBearerMiddle中被调用时正常工作,但是我无法获取令牌进行验证.

有没有人有这个工作与.net核心RC2?我在RC1上有同样的事情,但一直无法得到这个结果.

谢谢.

解决方法

从beta5开始(对于ASP.NET Core RC2),the OpenID Connect server middleware no longer uses JWT as the default format for access tokens.相反,它使用不透明令牌,由坚如磐石的ASP.NET核心数据保护堆栈加密(与身份验证Cookie完全相同).

您有3个选项可以解决您所看到的错误

>使用开发的new OAuth2 validation middleware支持不透明令牌(推荐的选项,如果您的API和您的授权服务器是同一应用程序的一部分).为此,请保留您在project.json中的AspNet.Security.OAuth.Validation引用,并通过app.USEOAuthValidation()替换app.UseJwtBearerAuthentication(…).您也可以从project.json中删除Microsoft.AspNetCore.Authentication.JwtBearer.

>强制OpenID Connect服务器中间件通过调用options来使用JWT令牌.AccessTokenHandler = new JwtSecurityTokenHandler();在选项中.请注意,您还必须致电ticket.SetResources(…)以将适当的受众附加到JWT令牌(有关详细信息,请参阅此处SO post).

>使用new introspection middleware.此选项更复杂,需要实施ValidateIntrospectionRequest事件来验证客户端凭据.只有当你知道你在做什么,才能使用它.

原文链接:https://www.f2er.com/aspnet/246184.html

猜你在找的asp.Net相关文章