我正在使用版权声明来处理授权的简单示例。
为清楚起见,我正在使用ASP.NET Core 2.2.4
startup.cs配置为:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
...
services.AddIdentity<IdentityUser, IdentityRole>(option => { option.Password = new PasswordOptions { ... }; };
services.ConfigureApplicationCookie(option => { option.LoginPath = "/logins/Index"; });
services.AddAuthorization(option =>
{
option.AddPolicy("EditorOver18Policy", policy =>
{
policy.RequireClaim("Over18Claim");
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc(routes =>
{ ... });
}
在登录期间建立了声明:
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (!ModelState.IsValid)
{ ... }
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);
if (!result.Succeeded)
{ ... }
var claims = new List<Claim>();
claims.Add(new Claim("Over18Claim", "True"));
var claimIdentity = new ClaimsIdentity(claims);
User.AddIdentity(claimIdentity);
if (!string.IsNullOrEmpty(model.ReturnUrl))
return Redirect(model.ReturnUrl);
return RedirectToAction("Display", "Photos");
}
要保护的控制器为:
[Authorize (policy: "EditorOver18Policy")]
public IActionResult Upload()
{
...
}
坦率地说,在运行该应用程序时,请确保我刚刚登录并因此获得了索赔,但我收到访问被拒绝的错误(很抱歉,如果使用的是葡萄牙语):
我想念什么?
答案 0 :(得分:1)
要添加自定义声明,您可以实现自定义IUserClaimsPrincipalFactory
或将UserClaimsPrincipalFactory
用作基类:
public class ApplicationClaimsIdentityFactory : Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory<IdentityUser>
{
UserManager<IdentityUser> _userManager;
public ApplicationClaimsIdentityFactory(UserManager<IdentityUser> userManager,
IOptions<IdentityOptions> optionsAccessor) : base(userManager, optionsAccessor)
{ }
public async override Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
{
var principal = await base.CreateAsync(user);
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim("Over18Claim", "true")
});
return principal;
}
}
然后在ConfigureServices
的{{1}}功能中注册:
Startup.cs