授权属性无法与ASP.Net Core中的JWT访问令牌一起使用

时间:2019-08-13 10:28:27

标签: asp.net-core jwt jwt-auth

尝试使用Ast.Net Core应用程序设置JWT,并以某种方式在方法中使用[Authorize]属性时显示 Bearer error =“ invalid_token”

不确定我在这里缺少什么。

AppSettings:

"Jwt": {
  "Key": "ThisisaKeyforAPIAccess",
  "Issuer": "TestSite.com"
}

生成访问令牌的方法:

var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(issuer: _config["Jwt:Issuer"],
                                         audience: _config["Jwt:Issuer"],
                                         expires: DateTime.Now.AddMinutes(10),
                                         signingCredentials: credentials);

        return new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token),
            expiration = token.ValidTo
        };

Auth.cs(用于检查令牌)

        public static IServiceCollection AddAuthentication(this IServiceCollection services, IConfiguration configuration)
    {
        var issuerID = configuration.GetSection("Jwt").GetValue<string>("Issuer");

        services.AddAuthentication(
            option => {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }
            ).
            AddJwtBearer(options => {
                options.SaveToken = true;
                options.RequireHttpsMetadata = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = issuerID,
                    ValidIssuer = issuerID,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]))
                };
            });

        return services;
    }

最后进入Startup.cs

services.AddAuthentication(_configuration);

        services.AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
        });

以及启动类的Configure方法中

         public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseAuthentication();
            app.UseMvc();
}

如果我使用[Authorize]属性,则该方法上的令牌无效。不确定我在这里缺少什么。

0 个答案:

没有答案