【发布时间】:2021-10-15 10:21:09
【问题描述】:
在我的网站上,用户根据登录时的三件事进行身份验证
- 用户ID
- 角色 ID
- 站点 ID
现在检查所有这些并用户登录后,问题是,例如,如果用户在站点 1 上具有管理员角色,并且在站点 2 中具有正常角色,如果在登录时他选择站点 2,他具有正常角色。他以管理员身份登录。所以我想在登录时捕获角色 id 并能够在我的布局视图中使用它。我在搜索“ActionFilterAttribute”时发现了这一点,这使我可以在任何地方使用 ViewBage。但是现在我如何将这个登录的用户角色 ID 传递给这个“ActionFilterAttribute”并将它添加到 ViewBag 并能够在我的网站上的任何地方使用它。我没有找到任何可以帮助我实现这一目标的方法。
这是我在 AccountController 中的登录操作
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await userManager.FindByNameAsync(model.userName);
var id = await userManager.FindByIdAsync(user.Id);
var query = (from st in dbContext.UserRoles
where st.UserId == user.Id
select st.RoleId).ToList();
if (user != null && AuthenticateAD(model.userName, model.Password))
{
for (int i=0; i<query.Count;i++)
{
if (await applicationUserManager.IsInRoleByIdAsync(id, query[i],
model.sites))
{
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
model.RoleId = query[i];
await signInManager.SignInAsync(user, false);
return RedirectToAction("Index", "Home", query[i]);
}
}
else
{
ModelState.AddModelError("", "Not Authorized");
}
}
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
这是我的布局,我检查登录用户是否在角色管理员中。现在,如果我从 Login 传递了角色 ID,我希望能够在这里使用它
@if (signInManager.IsSignedIn(User) && User.IsInRole("Admin") )
{
Here it shows ManageUser option
}
验证AD
public bool AuthenticateAD(string username, string password)
{
using (var context = new PrincipalContext(ContextType.Domain,
"xxx.com"))
{
return context.ValidateCredentials(username, password);
}
}
如果有任何方法可以将角色 ID 传递给布局,那就太好了。提前感谢任何回答的人
我找到的ActionFilterAttribute 代码在这里ActionFilterAttribute @Mohammad Karimi
【问题讨论】:
-
您能分享一下您是如何登录用户并在方法
AuthenticateAD中启动用户会话的吗? -
@Chetan 它使用用户原则在 Active Directory 上验证用户群。我会发布它
标签: c# asp.net-core model-view-controller asp.net-core-mvc