我在使用活动目录来管理我的用户和他们各自的角色,这两个都是正确带回来的。
然后我试图通过以下方式分配角色 ClaimsIdentity.AddClaim(new Claim(ClaimsType.Role, user.Role));
调试时,我可以看到角色被分配了,而且我没有得到任何错误。
在我的主控制器中,我添加了 [Authorize(Roles = "Admin")]
的IActionResult上,但当我导航到 "关于 "页面时,我又回到了登录页面。
用户是被授权的,因为我把 [Authorize]
上的联系,并且登录后可以进入这个页面。
我错过了什么,使角色数据属性无法使用?
账户控制器登录代码。
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var usr = await AuthorisationCore.AuthenticateUser(model.Username, model.Password);
if(usr.IsAuthenticated)
{
// setting up claims identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, usr.Username),
};
// adding role to the claim
var identity = new ClaimsIdentity(claims, "cookie");
identity.AddClaim(new Claim(ClaimTypes.Role, usr.Role));
// new claim principal with the identity of the user input
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("SecurityCookie", principal, new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddHours(1)
});
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
return View();
}
启动代码:
public void ConfigureServices(IServiceCollection services)
{
// data attributes like [AllowAnonymous]
services.AddAuthorization();
// allows for use of cookies and to add options to them
services
.AddAuthentication("SecurityCookie")
.AddCookie("SecurityCookie", cfg =>
{
cfg.SlidingExpiration = true;
cfg.LoginPath = "/Account/Login";
cfg.AccessDeniedPath = "/Account/Login";
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
你必须同时使用 app.UseAuthorization();
和 app.UseAuthentication();
在启动阶段 Configure
功能