获得令牌后,无法使用jwt访问授权路由

时间:2017-05-23 18:47:45

标签: .net-core jwt openiddict

我可以登录并获得一个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();
        }
    }
}

我已经尝试将权威和受众设置为各种不同的东西。我已经尝试完全删除它们,但我无法在

的路线上获得200
  

[授权]

已添加。

当我尝试在Postman中执行此操作时,我收到错误

  

Bearer error =“invalid_token”,error_description =“签名是   无效“

这是一个带有1个标题的GET,Authorization = bearer {token here} 我只是不知所措。已经在这3天了。我觉得这几乎是正确的,我只是错过了一些关键的事情。缺少标题或其他内容。

另请注意,我在localhost:4200有一个有角度的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"}}}}

1 个答案:

答案 0 :(得分:2)

叹息。我是个白痴。

如果您签署了密钥

options.AddSigningKey(signingKey);

然后你需要告诉

  

app.UseJwtBearerAuthentication

如何验证该密钥。

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