我使用Active Directory来管理我的用户及其各自的角色,这些都被正确地带回来。
然后我在调试时尝试通过ClaimsIdentity.AddClaim(new Claim(ClaimsType.Role, user.Role));
分配角色我可以看到角色已分配且我没有收到任何错误。
在我的家庭控制器中,我已经在关于的IActionResult上添加了[Authorize(Roles = "Admin")]
,但是当我导航到关于页面时,我将被重新登录到登录。
用户已获得授权,因为我将[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?}");
});
}
答案 0 :(得分:1)
在启动app.UseAuthorization();
函数中必须同时使用app.UseAuthentication();
和Configure