[Authorize属性在升级到NET Core 3.1后始终返回401

问题描述 投票:0回答:1

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

我最近将API从核心2更新为核心3.1,这使我相信代码在2和3.1之间有所不同。

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

下面是几段代码:

Startup.cs-ConfigureServices

    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-GenerateToken

    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个回答
0
投票

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

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]` 

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

并且在您的服务中注册该模式,如

services.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
   ...
© www.soinside.com 2019 - 2024. All rights reserved.