【问题标题】:Authorize attribute always returns 401 after upgrading to NET Core 3.1升级到 NET Core 3.1 后,Authorize 属性始终返回 401
【发布时间】:2020-05-25 17:43:06
【问题描述】:

我的 NET Core 3.1 REST API 当前在标记有 [Authorize] 属性的调用上返回 401。没有授权属性的调用,或者允许匿名的调用,或者如果我从控制器中删除了授权属性,都是成功的。

我最近将 API 从 Core 2 更新到 core 3.1,这让我相信代码在 2 到 3.1 之间的预期不同。

通过查看 StackOverflow 和在线上的其他问题,大多数都指向启动时配置功能中的项目顺序,尽管我的看起来与 Microsoft 文档中的内容相匹配。我没有更改我的令牌生成代码,因为当我收到它们并在 JWT.io 中测试它们时,从 2 更新到 3.1 令牌看起来确实有效,但与以前一样,当通过 Postman 运行调用时,或从前端应用程序调用立即 401s在授权步骤。

下面是一些sn-ps的代码:

Startup.cs - 配置服务

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddControllers();

        // Get appsettings from config file
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);
        var appSettings = appSettingsSection.Get<AppSettings>();

        services.AddDbContext<MuglensContext>(options => options.UseSqlServer(appSettings.DBConnection));

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.JWTKey))
            };
        });
        // Underneath this is adding of scoped services

Startup.cs - 配置

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(builder => builder
            .WithOrigins(Configuration["Origins"])
            .AllowAnyHeader()
            .AllowAnyMethod()
        );

        //AuthAppBuilderExtensions.UseAuthentication(app);
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

    }

AuthService.cs - 生成令牌

    private string GenerateToken(string email, string userID)
    {
        var claims = new[]
        {
            new Claim("email", email),
            new Claim("userID", userID)
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.JWTKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: _settings.Origins,
            audience: _settings.Origins,
            claims: claims,
            expires: DateTime.Now.AddMinutes(45),
            signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

任何帮助将不胜感激。

【问题讨论】:

    标签: c# .net-core-3.1 authorize-attribute


    【解决方案1】:

    您是否尝试过针对 Authoize 属性中的 JWT 架构进行验证?

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]` 
    

    在命名空间Microsoft.AspNetCore.Authentication.JwtBearer

    并在您的服务中注册该架构,例如

    services.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
    {
       ...
    

    【讨论】:

    • 很遗憾,这不起作用。我相信这已经包含在 Configure 方法 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    【解决方案2】:

    我从该项目中休息了相当长的一段时间,但在上周回来时想通了。问题是由于我在初创公司中的受众和发行人设置造成的。我将 ValidateIssuer ValidateAudience 值设置为 true,但 ValidIssuer 和 ValidAudience 中没有任何值。

    填充这些值后,代码看起来像预期的那样工作。

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 2021-10-13
      • 2020-04-22
      • 2020-04-04
      • 2022-06-13
      • 2021-03-25
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      相关资源
      最近更新 更多