首页 > 解决方案 > ASP.Net Core 3.1 Web API 中的授权不起作用

问题描述

我有一个具有基于角色的授权的 ASP.NET Core 3.1 和 Angular 11 应用程序,但是在运行该应用程序时,我收到错误 401 Unauthorized。

这是我的 Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddDbContext<DataContext>(opt =>
        {
            opt.UseSqlServer(Configuration.GetConnectionString("Connection"));
        });
        services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
        {
            options.Password.RequireDigit = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireLowercase = false;
            options.Password.RequireUppercase = false;
            options.Password.RequiredLength = 4;

        }).AddEntityFrameworkStores<DataContext>()
           .AddDefaultTokenProviders();
        #region JWT Config
        // configure strongly typed settings objects
        var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings:JWT_Secret"].ToString());

        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = false;
            x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                ClockSkew = TimeSpan.Zero
            };
        });
        #endregion
        services.AddCors();
        services.AddControllers().AddNewtonsoftJson();
        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });
    }

这是配置功能

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
      
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }
        app.UseRouting();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseCors(x => x.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod()
                .AllowCredentials());
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });
        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";
            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }

这是我的 Controller 类,我有适当的 Authorize 属性,像这样,

[Route("[controller]")]
[ApiController]
[Authorize(Roles = "admin")]
public class CharitiesController : ControllerBase
{
}

这是 applicationuser 表中的管理员记录 在 此处输入图像描述

applicationrole 表中的管理员角色记录在 此处输入图像描述

在此处输入图像描述

标签: asp.netangularasp.net-coreasp.net-web-apiauthorization

解决方案


推荐阅读