.net core 获取令牌后无法使用jwt访问授权路由

.net core 获取令牌后无法使用jwt访问授权路由,.net-core,jwt,openiddict,.net Core,Jwt,Openiddict,我可以登录并获得jwt { "resource": "resource-server", "token_type": "Bearer", "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4NzJlMTY5OS0xNGQwLTRhYmItYTU4Mi1kZDZmODkzNWU1NGEiLCJuYW1lIjoidGVzdEB0ZXN0LmNvbSIsInRva2VuX3VzYWdlIjoiYWNjZXNzX

我可以登录并获得jwt

{
  "resource": "resource-server",
  "token_type": "Bearer",
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4NzJlMTY5OS0xNGQwLTRhYmItYTU4Mi1kZDZmODkzNWU1NGEiLCJuYW1lIjoidGVzdEB0ZXN0LmNvbSIsInRva2VuX3VzYWdlIjoiYWNjZXNzX3Rva2VuIiwianRpIjoiNzdlMDhiMGMtMGRmMy00NDJjLTgxOTItMDk4YWNiYjdiZWQyIiwiYXVkIjoicmVzb3VyY2Utc2VydmVyIiwibmJmIjoxNDk1NTY0ODI5LCJleHAiOjE0OTU1Njg0MjksImlhdCI6MTQ5NTU2NDgyOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1NTY2NC8ifQ.00X9de2jtetmWoj4BNaskvtPryElEsenpoVgisCxEoA",
  "expires_in": 3600
}
但当我试图得到一条受保护的路线时,我得到了401

这是我的startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Authorization.Data;
using Authorization.Models;
using Authorization.Services;

using OpenIddict.Core;
using OpenIddict.Models;
using AspNet.Security.OpenIdConnect.Primitives;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Authorization
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets<Startup>();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddCors();

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
                options.UseOpenIddict();
            });



            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
                {
                    options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                    options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                    options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
                });

            var secretKey = "mysupersecret_secretkey!123";
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));


            services.AddOpenIddict(options =>
                {
                    options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
                    options.AddMvcBinders();
                    options.EnableTokenEndpoint("/connect/token");
                    options.UseJsonWebTokens();
                    options.AllowPasswordFlow();
                    options.AddSigningKey(signingKey);
                    options.DisableHttpsRequirement();
                });


            services.AddMvc();

            // Add application services.
            //services.AddTransient<IEmailSender, AuthMessageSender>();
            //services.AddTransient<ISmsSender, AuthMessageSender>();
        }

        // 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();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseCors(builder =>
            {
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowCredentials();
                builder.AllowAnyOrigin(); // For anyone access.
                                          //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url.
            });

            app.UseStaticFiles();



            //app.UseOAuthValidation();
            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                Authority = "http://localhost:55664",
                Audience = "resource-server",
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                RequireHttpsMetadata = false,

            });

            app.UseOpenIddict();

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





            app.UseMvcWithDefaultRoute();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Identity.EntityFrameworkCore;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Logging;
使用授权数据;
使用授权模型;
使用授权服务;
使用OpenIddict.Core;
使用OpenIddict.Models;
使用AspNet.Security.OpenIdConnect.Primitives;
使用Microsoft.AspNetCore.Authentication.JwtBearer;
使用Microsoft.IdentityModel.Tokens;
使用系统文本;
命名空间授权
{
公营创业
{
公共启动(IHostingEnvironment环境)
{
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:false,reloadOnChange:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:true);
if(env.IsDevelopment())
{
//有关使用用户机密存储的更多详细信息,请参阅https://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration=builder.Build();
}
公共IConfigurationRoot配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddCors();
//添加框架服务。
services.AddDbContext(选项=>
{
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”);
options.UseOpenIddict();
});
服务.额外性()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
配置(选项=>
{
options.ClaimsIdentity.UserNameClaimType=OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType=OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType=OpenIdConnectConstants.Claims.Role;
});
var secretKey=“mysupersecret\u secretKey!123”;
var-signingKey=new-SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
services.AddOpenIddict(选项=>
{
options.AddEntityFrameworkCoreStores();
options.AddMvcBinders();
options.EnableTokenEndpoint(“/connect/token”);
options.UseJsonWebTokens();
options.AllowPasswordFlow();
选项。添加signingKey(signingKey);
选项。禁用HttpSrequirement();
});
services.AddMvc();
//添加应用程序服务。
//services.AddTransient();
//services.AddTransient();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
loggerFactory.AddConsole(Configuration.GetSection(“Logging”);
loggerFactory.AddDebug();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseCors(builder=>
{
builder.AllowAnyHeader();
builder.AllowAnyMethod();
builder.AllowCredentials();
builder.AllowAnyOrigin();//供任何人访问。
//corsBuilder.WithOrigins(“http://localhost:56573“”;//用于特定的url。
});
app.UseStaticFiles();
//app.useAuthValidation();
应用程序UseJWTBeareAuthentication(新JWTBeareOptions
{
权威=”http://localhost:55664",
访问群体=“资源服务器”,
自动验证=真,
自动挑战=正确,
RequireHttpsMetadata=false,
});
app.UseOpenIddict();
//在下面添加外部身份验证中间件。要配置它们,请参阅https://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvcWithDefaultRoute();
}
}
}
我试着为各种不同的事情设置权威和听众。我已经试着把它们完全移除了,但是我不能用它在一条路线上获得200

[授权]

加上

当我尝试在《邮递员》中这样做时,我得到了错误

承载错误=“无效的令牌”,错误描述=“签名无效” 无效“

这是一个带有1个头的GET,Authorization=bearer{token here} 我只是不知所措。我已经做了三天了。我觉得这几乎是对的,我只是错过了一些关键的东西。缺少标题或什么的

另外请注意,我在localhost:4200上有一个angular 2应用程序。但我的理解是,这应该在邮递员内部仍然有效

这是我点击授权路由时的服务器输出

Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.2832518Z","tags":{"ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.operation.id":"0HL5214V879CK","ai.application.ver":"1.0.0.0"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Request starting HTTP/1.1 GET http://localhost:55664/api/values","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Hosting.Internal.WebHost","Protocol":"HTTP/1.1","AspNetCoreEnvironment":"Development","DeveloperMode":"true","Scheme":"http","Host":"localhost:55664","Path":"/api/values","Method":"GET"}}}}
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:55664/api/values  
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.2902711Z","tags":{"ai.operation.name":"GET /api/values","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"The request path /api/values does not match a supported file type","severityLevel":"Verbose","properties":{"CategoryName":"Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware","{OriginalFormat}":"The request path {Path} does not match a supported file type","AspNetCoreEnvironment":"Development","DeveloperMode":"true","Path":"/api/values"}}}}
Exception thrown: 'Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException' in System.IdentityModel.Tokens.Jwt.dll
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3128307Z","tags":{"ai.operation.name":"GET /api/values","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Failed to validate the token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4NzJlMTY5OS0xNGQwLTRhYmItYTU4Mi1kZDZmODkzNWU1NGEiLCJuYW1lIjoidGVzdEB0ZXN0LmNvbSIsInRva2VuX3VzYWdlIjoiYWNjZXNzX3Rva2VuIiwianRpIjoiNzdlMDhiMGMtMGRmMy00NDJjLTgxOTItMDk4YWNiYjdiZWQyIiwiYXVkIjoicmVzb3VyY2Utc2VydmVyIiwibmJmIjoxNDk1NTY0ODI5LCJleHAiOjE0OTU1Njg0MjksImlhdCI6MTQ5NTU2NDgyOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1NTY2NC8ifQ.00X9de2jtetmWoj4BNaskvtPryElEsenpoVgisCxEoA.","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware","{OriginalFormat}":"Failed to validate the token {Token}.","Token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4NzJlMTY5OS0xNGQwLTRhYmItYTU4Mi1kZDZmODkzNWU1NGEiLCJuYW1lIjoidGVzdEB0ZXN0LmNvbSIsInRva2VuX3VzYWdlIjoiYWNjZXNzX3Rva2VuIiwianRpIjoiNzdlMDhiMGMtMGRmMy00NDJjLTgxOTItMDk4YWNiYjdiZWQyIiwiYXVkIjoicmVzb3VyY2Utc2VydmVyIiwibmJmIjoxNDk1NTY0ODI5LCJleHAiOjE0OTU1Njg0MjksImlhdCI6MTQ5NTU2NDgyOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1NTY2NC8ifQ.00X9de2jtetmWoj4BNaskvtPryElEsenpoVgisCxEoA","AspNetCoreEnvironment":"Development","DeveloperMode":"true","Exception":"Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10500: Signature validation failed. No security keys were provided to validate the signature.\r\n   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)\r\n   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)\r\n   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()"}}}}
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: Failed to validate the token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4NzJlMTY5OS0xNGQwLTRhYmItYTU4Mi1kZDZmODkzNWU1NGEiLCJuYW1lIjoidGVzdEB0ZXN0LmNvbSIsInRva2VuX3VzYWdlIjoiYWNjZXNzX3Rva2VuIiwianRpIjoiNzdlMDhiMGMtMGRmMy00NDJjLTgxOTItMDk4YWNiYjdiZWQyIiwiYXVkIjoicmVzb3VyY2Utc2VydmVyIiwibmJmIjoxNDk1NTY0ODI5LCJleHAiOjE0OTU1Njg0MjksImlhdCI6MTQ5NTU2NDgyOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1NTY2NC8ifQ.00X9de2jtetmWoj4BNaskvtPryElEsenpoVgisCxEoA.

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10500: Signature validation failed. No security keys were provided to validate the signature.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3173431Z","tags":{"ai.operation.name":"GET /api/values","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Bearer was not authenticated. Failure message: IDX10500: Signature validation failed. No security keys were provided to validate the signature.","severityLevel":"Information","properties":{"FailureMessage":"IDX10500: Signature validation failed. No security keys were provided to validate the signature.","CategoryName":"Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware","AuthenticationScheme":"Bearer","{OriginalFormat}":"{AuthenticationScheme} was not authenticated. Failure message: {FailureMessage}","AspNetCoreEnvironment":"Development","DeveloperMode":"true"}}}}
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: Bearer was not authenticated. Failure message: IDX10500: Signature validation failed. No security keys were provided to validate the signature.
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3238602Z","tags":{"ai.operation.name":"GET /api/values","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Request successfully matched the route with name '(null)' and template 'api/Values'.","severityLevel":"Verbose","properties":{"CategoryName":"Microsoft.AspNetCore.Routing.Tree.TreeRouter","{OriginalFormat}":"Request successfully matched the route with name '{RouteName}' and template '{RouteTemplate}'.","AspNetCoreEnvironment":"Development","DeveloperMode":"true","RouteTemplate":"api/Values"}}}}
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3253638Z","tags":{"ai.operation.name":"GET /api/values","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Action 'AspToken.Controllers.ValuesController.Post (Authorization)' with id 'd8fd53b2-6692-4c31-b8ce-0d7965e7e5b1' did not match the constraint 'Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint'","severityLevel":"Verbose","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.Internal.ActionSelector","{OriginalFormat}":"Action '{ActionName}' with id '{ActionId}' did not match the constraint '{ActionConstraint}'","AspNetCoreEnvironment":"Development","ActionConstraint":"Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint","ActionId":"d8fd53b2-6692-4c31-b8ce-0d7965e7e5b1","DeveloperMode":"true","ActionName":"AspToken.Controllers.ValuesController.Post (Authorization)"}}}}
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3273695Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Executing action AspToken.Controllers.ValuesController.Get (Authorization)","severityLevel":"Verbose","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker","{OriginalFormat}":"Executing action {ActionName}","AspNetCoreEnvironment":"Development","DeveloperMode":"true","ActionName":"AspToken.Controllers.ValuesController.Get (Authorization)"}}}}
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3293745Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Authorization failed for user: (null).","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Authorization.DefaultAuthorizationService","{OriginalFormat}":"Authorization failed for user: {UserName}.","AspNetCoreEnvironment":"Development","DeveloperMode":"true"}}}}
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: (null).
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3323827Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker","{OriginalFormat}":"Authorization failed for the request at filter '{AuthorizationFilter}'.","AuthorizationFilter":"Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter","AspNetCoreEnvironment":"Development","DeveloperMode":"true"}}}}
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3348898Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Executing ChallengeResult with authentication schemes ().","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.ChallengeResult","{OriginalFormat}":"Executing ChallengeResult with authentication schemes ({Schemes}).","AspNetCoreEnvironment":"Development","DeveloperMode":"true","Schemes":"System.String[]"}}}}
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3378977Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"AuthenticationScheme: Bearer was challenged.","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware","AuthenticationScheme":"Bearer","{OriginalFormat}":"AuthenticationScheme: {AuthenticationScheme} was challenged.","AspNetCoreEnvironment":"Development","DeveloperMode":"true"}}}}
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: AuthenticationScheme: Bearer was challenged.
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3409055Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Executed action AspToken.Controllers.ValuesController.Get (Authorization) in 11.408ms","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker","ElapsedMilliseconds":"11.408","{OriginalFormat}":"Executed action {ActionName} in {ElapsedMilliseconds}ms","AspNetCoreEnvironment":"Development","DeveloperMode":"true","ActionName":"AspToken.Controllers.ValuesController.Get (Authorization)"}}}}
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action AspToken.Controllers.ValuesController.Get (Authorization) in 11.408ms
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3439137Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Connection id \"0HL5214V6KQ2K\" completed keep alive response.","severityLevel":"Verbose","properties":{"CategoryName":"Microsoft.AspNetCore.Server.Kestrel","{OriginalFormat}":"Connection id \"{ConnectionId}\" completed keep alive response.","AspNetCoreEnvironment":"Development","DeveloperMode":"true","ConnectionId":"0HL5214V6KQ2K"}}}}
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-05-23T18:49:45.3454177Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Request finished in 61.7295ms 401","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Hosting.Internal.WebHost","ElapsedMilliseconds":"61.7295","StatusCode":"401","AspNetCoreEnvironment":"Development","DeveloperMode":"true"}}}}
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 61.7295ms 401 
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2017-05-23T18:49:45.3318446Z","tags":{"ai.operation.name":"GET Values/Get","ai.internal.nodeName":"GA-BRU-D9V2XBH2","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.cloud.roleInstance":"GA-BRU-D9V2XBH2","ai.operation.id":"0HL5214V879CL","ai.application.ver":"1.0.0.0","ai.location.ip":"::1"},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"5sE5TCp7osw=","name":"GET Values/Get","duration":"00:00:00.0180848","success":false,"responseCode":"401","url":"http://localhost:55664/api/values","properties":{"httpMethod":"GET","AspNetCoreEnvironment":"Development","DeveloperMode":"true"}}}}
Application Insights Telemetry(未配置):{“名称”:“Microsoft.ApplicationInsights.Dev.Message”,“时间”:“2017-05-23T18:49:45.2832518Z”,“标记”:{“ai.internal.sdkVersion”:“aspnet5c:2.0.0”,“ai.operation.id”:“0HL5214V”
options.AddSigningKey(signingKey);
TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = signingKey,

                    ValidateIssuer = true,                        

                    ValidateAudience = true,
                    ValidAudience = audience,

                    ValidateLifetime = true,
                }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Authorization.Data;
using Authorization.Models;
using Authorization.Services;

using OpenIddict.Core;
using OpenIddict.Models;
using AspNet.Security.OpenIdConnect.Primitives;

using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Authorization
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets<Startup>();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddCors();

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
                options.UseOpenIddict();
            });



            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
                {
                    options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                    options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                    options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
                });

            var secretKey = "mysupersecret_secretkey!123";
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));


            services.AddOpenIddict(options =>
                {
                    options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
                    options.AddMvcBinders();
                    options.EnableTokenEndpoint("/connect/token");
                    options.UseJsonWebTokens();
                    options.AllowPasswordFlow();
                    options.AddSigningKey(signingKey);
                    options.DisableHttpsRequirement();
                });


            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

        // 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();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseCors(builder =>
            {
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowCredentials();
                builder.AllowAnyOrigin(); // For anyone access.
                                          //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url.
            });

            app.UseStaticFiles();

            var audience = "resource-server";
            var authority = "http://localhost:55664";

            var secretKey = "mysupersecret_secretkey!123";
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            //app.UseOAuthValidation();
            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                Authority = authority,
                Audience = audience,
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                RequireHttpsMetadata = false,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = signingKey,

                    ValidateIssuer = true,
                    // makes no difference seemingly being ignored
                    //ValidIssuer = Configuration.Get<AppOptions>().Jwt.Authority,

                    ValidateAudience = true,
                    ValidAudience = audience,

                    ValidateLifetime = true,
                }

            });

            app.UseOpenIddict();

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





            app.UseMvcWithDefaultRoute();
        }
    }
}