【问题标题】:Authorize attribute is not working in JWT and asp.net core 2.1授权属性在 JWT 和 asp.net core 2.1 中不起作用
【发布时间】:2020-07-21 15:35:42
【问题描述】:

我已经为 .net 核心客户端实现了 JWT,但是当我设置授权属性时,它每次都会给我 401 未经授权的响应。 我尝试在中间件的属性中提到模式名称。更改序列。通过堆栈溢出的大量链接。

下面是startup.cs

public void ConfigureServices(IServiceCollection services)
{
        services.AddSwaggerDocumentation();

        services.ConfigureCors();

        services.ConfigureIISIntegration();

        services.ConfigureLoggerService();

        services.ConfigureSqlContext(Configuration);

        services.ConfigureRepositoryWrapper();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,

                ValidIssuer = "http://localhost:5000",
                ValidAudience = "http://localhost:4200/",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
            };
        });

        services.AddMvc();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger)
    {

        app.UseSwaggerDocumentation();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();                
        }

        app.UseHttpStatusCodeExceptionMiddleware();

        app.UseCors("CorsPolicy");

        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.All
        });

        app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404
                && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html";
                await next();
            }
        });


        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvc();
    }

下面是JWT初始化代码

if (userInfo.Any(c => c.ValidUser == "Y"))
                    {
                        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));

                        var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                        var claims = new List<Claim>
                            {
                                new Claim(ClaimTypes.Name, vsecGetPasswordByUserName.LoginId),
                                new Claim(ClaimTypes.Role, "Admin")
                            };

                        var tokeOptions = new JwtSecurityToken(
                            issuer: "http://localhost:5000",
                            audience: "http://localhost:4200",
                            claims: claims,
                            expires: DateTime.Now.AddMinutes(5),
                            signingCredentials: signinCredentials
                        );

                        var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

                        return Ok(new { UserInfo = userInfo, TokenString = tokenString });
                    }
                    else
                    {
                        throw new HttpStatusCodeException(StatusCodes.Status401Unauthorized, @"User not valid");
                    }
                }

这是提到授权属性的控制器代码

[Authorize]
[EnableCors("CorsPolicy")]
[ApiController]
[Route("api/Utility")]
public class UtilityController : ControllerBase

【问题讨论】:

    标签: c# asp.net asp.net-core jwt


    【解决方案1】:

    您在Startup 类的Configure 方法中缺少UseAuthorization 中间件。

    如下:

    app.UseAuthentication();
    app.UseAuthorization(); // <-- Here it is
    

    【讨论】:

    • 找不到这个中间件需要加包吗?
    • 使用using Microsoft.AspNetCore.Builder;命名空间。
    • @TanvirArjel app.UseAuthorization() 根据doco 仅适用于 NET Core 3.0 及更高版本。该问题针对 NET Core 2.1
    • 无法在此命名空间或 Microsoft.AspNetCore.Authentication 下找到
    【解决方案2】:

    请注意您的TokenValidationParameters,您的audiencehttp://localhost:4200/,与令牌声明中的(http://localhost:4200)不匹配:

    所以只需将TokenValidationParameters 中的ValidAudience 修改为:

    ValidAudience = "http://localhost:4200",
    

    【讨论】:

    • 感谢您的建议,但仍然是相同的响应。我也在大摇大摆地尝试。
    • 使用 Fiddler 追踪 401 并检查是否返回任何详细错误,并在属性中设置架构名称
    • 我已经修改了 JWT 初始化
    • //services.AddAuthorization(auth => //{ // auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() // .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) // .RequireAuthenticatedUser()。建造()); //}); //services.AddAuthentication(options => //{ // options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; // options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; //}) 和提到的架构名称
    • 我的意思是设置了带有Authorize属性的方案,如果还是401,你可以使用fiddler或者开发工具来追踪WWW-Authenticate响应头中的内部错误信息
    【解决方案3】:

    我的令牌架构是 持有者:{'Token':'Abcsdsdsgddcdsa'}

    我将架构更改为

    承载者:'Asdsaasadcaca'

    它按预期工作

    【讨论】:

      猜你喜欢
      • 2018-08-19
      • 2018-09-07
      • 1970-01-01
      • 2019-07-23
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2019-09-29
      相关资源
      最近更新 更多