首页 > 解决方案 > 升级到 NET Core 3.1 后,Authorize 属性始终返回 401

问题描述

我的 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在授权步骤。

下面是一些代码片段:

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.1authorize-attribute

解决方案


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

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]` 

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

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

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

推荐阅读