asp.net - 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 表中的管理员角色记录在 此处输入图像描述
解决方案
推荐阅读
- amazon-web-services - 如何使用 Cloudfront 将裸域重定向到 www?
- python - 使用 DictReader 读取 csv 文件可能有哪些优点和缺点?
- ios - 在 UITableViewCell 内显示 youtube 视频缩略图和标题
- batch-file - UAC 提示后恢复批处理文件
- python - 动态sql查询(字符串模板)
- excel - 元素未从数组中获取值
- java - 在不使用中断的情况下正确终止 Java 可调用线程?
- android - 无法运行程序“/data/data/my.app.package/files/my-executable”:错误=13,权限被拒绝
- javascript - 2个具有相同类名的css文件,并且具有该类名的元素具有两种样式
- plotly-dash - 在 Google Chrome 上运行 Plotly Dash 应用程序的问题