Authorize Attribute not working with JWT Access Token in ASP.Net Core

核能气质少年 提交于 2021-02-11 10:26:08

问题


Trying to setup JWT with Ast.Net Core app and somehow when I use the [Authorize] attribute on the method it shows Bearer error="invalid_token"

Not sure what I am missing here.

AppSettings:

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

Method to generate Access Token:

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 (To Check Token)

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

and finally in Startup.cs

services.AddAuthentication(_configuration);

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

and in Configure method for Startup class

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

If I use the [Authorize] attribute I am getting invalid token on the method. Not sure what I am missing here.

来源:https://stackoverflow.com/questions/57475858/authorize-attribute-not-working-with-jwt-access-token-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!