[英].NET Core MVC add role claim to local user when in development before authorization
我正在尋找一種“簡單”的方法來自動向本地用戶添加角色聲明,以測試我的授權邏輯。 也就是說,想要在我的控制器授權之前向本地用戶添加一些特定的聲明。
我了解到,過去可以對控制器執行類似的操作:
#if DEBUG
protected override void OnAuthorization(AuthorizationContext filterContext)
{
var roles = new[] { "role-under-test"};
HttpContext.User = new GenericPrincipal(new GenericIdentity("DebugUser"), roles);
base.OnAuthorization(filterContext);
}
#endif
但這要早於我現在正在使用的.NET Core。 慢慢地,我一直在處理下面介紹的代碼,這似乎很有效,但是與上述示例相比,顯然要麻煩得多。 所以我的問題是,是否有人知道更好,更輕松的方式來實現這一目標?
定制授權屬性:
public class CustomAuthAttribute : RolesAuthorizationRequirement {
public CustomAuthAttribute(IEnumerable<string> allowedRoles) : base(allowedRoles) { }
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolesAuthorizationRequirement requirement) {
#if DEBUG
context.User.AddIdentity(new ClaimsIdentity(new GenericIdentity("DebugUser"), new[] {
new Claim(ClaimsIdentity.DefaultRoleClaimType, "users"),
new Claim(ClaimsIdentity.DefaultRoleClaimType, "admins")
}));
#endif
return base.HandleRequirementAsync(context, requirement);
}
}
在Startup.cs中
public void ConfigureServices(IServiceCollection services) {
// ...
services.AddAuthorization( options =>
options.AddPolicy("UsersAndAdmins",
policy => policy.AddRequirements(new CustomAuthAttribute(new []{"users", "admins"}))));
}
然后在控制器中使用它:
[Authorize(Policy = "UsersAndAdmins")]
public class HomeController : Controller {
// ...
您想要索賠轉換;
寫一個看起來像這樣的聲明轉換
public class ClaimsTransformer : IClaimsTransformer
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
{
((ClaimsIdentity)context.principal.Identity).AddClaim(new Claim("Admin", "true"));
return Task.FromResult(principal);
}
}
並將其連接到startup.cs
Configure
中
app.UseClaimsTransformation(new ClaimsTransformationOptions
{
Transformer = new ClaimsTransformer()
});
當然,如果要進行測試,則可以將其包裝在環境檢查中,以確保您處於開發環境中:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.