c# - 具有基于自定义角色的授权的 ASP.Net Core 3.0 Windows 身份验证
问题描述
我希望在 ASP.NET 3.0 MVC 应用程序中使用 Windows 身份验证,并从 SQL 数据库中提取角色以实现 API 安全性。我将用类似的东西装饰 API 控制器方法[Authorize(Roles = "Admin")]
我在这里拥有的很多东西,我都是从这个网站上获得的,但我被困在最后一部分。我可以看到该角色已应用于用户,但无法获得授权工作。
为此,我首先从 ClaimsTransformer 开始,它将用于通过声明向我的用户应用角色。
ClaimsTransformer.cs
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
//This sample will automatically apply the Admin role to the user
//In the real app, I will check the user against my DB and apply all roles (as claims) here
var ci = (ClaimsIdentity)principal.Identity;
var c = new Claim(ci.RoleClaimType, "Admin");
ci.AddClaim(c);
return await Task.FromResult(principal);
}
Startup.cs - 配置服务
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//Register the ClaimsTransformer here
services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
//Use windows authentication
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthorization();
}
Starup.cs - 配置
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
数据控制器.cs
在 API 控制器中,我可以像这样设置一个没有授权的方法,并在检查 User.IsInRole("Admin"); 时看到结果显示为 true;
[HttpGet]
public async Task<IActionResult> GetData1()
{
var result = User.IsInRole("Admin");
return Ok(result);
}
但是,如果我用这样的方式装饰控制器方法[Authorize(Roles = "Admin")]
,那么我会在调用此方法时收到 Forbidden 响应。
[HttpGet]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetData1()
{
var result = User.IsInRole("Admin");
return Ok(result);
}
解决方案
在这种情况下,切换行是一个小但常见的错误,顺序是UseAuthentication
(谁是用户)然后UseAuthorization
是(用户允许做什么)。这就解释了为什么授权不起作用。
推荐阅读
- r - 生成两个具有预定义相关性的负二项分布随机变量
- javascript - 无法在 GET 上运行
- flutter - 颤振医生命令没有响应
- javascript - 添加两个对象而不覆盖对象Javascript中的键
- javascript - 根据两个值按字母顺序对数组中的对象进行排序
- c++ - 出现 C2059 错误后在 Visual Studio 中恢复 iomanip
- python - 使用 scapy 发送嗅探到的数据包
- typescript - 导航回时如何在 React Native 中刷新缓存的屏幕
- javascript - 在 React 中处理自定义事件
- python - 如何使用函数跳出 for 循环?