【发布时间】:2019-04-21 20:05:04
【问题描述】:
我已经设置了我的应用程序,它使用身份在站点上进行角色访问。
我正在从使用自定义声明转换器的 Windows 身份验证切换到使用 LDAP,这样用户将拥有一个登录页面,这与 chrome 中弹出的“javascript alert like”windows 身份验证不同。
问题是,即使我在 LDAP 中找到要登录的用户以及在应用程序中找到具有角色的用户,它仍然没有登录。 SignInAsync 函数执行时没有任何问题,但在重定向时仍显示未登录。我的 CookieAuthentication 设置有问题还是我错了。 _LoginPartial 仍然显示登录。
我目前的设置是:
配置服务
services.AddIdentity<User, Role>(options =>
{
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_\\";
}).AddEntityFrameworkStores<VIPADBContext>();
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/UserAccounts/AccessDenied";
options.Cookie.Name = CookieAuthenticationDefaults.AuthenticationScheme;
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.LoginPath = "/UserAccounts/Login";
options.SlidingExpiration = true;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "UserAccounts/Login";
});
配置
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseCookiePolicy();
自定义登录管理器
public class SignInManager : ISignInManager
{
private readonly IHttpContextAccessor _httpContextAccessor;
public SignInManager(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task SignInAsync(User user, IList<string> roleNames)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
};
foreach (string roleName in roleNames)
{
claims.Add(new Claim(ClaimTypes.Role, roleName));
}
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
}
public async Task SignOutAsync()
{
await _httpContextAccessor.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
具有登录和注销功能的 UserAccountsController
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
try
{
var user = _authService.Login(model.Username, model.Password);
if (user != null)
{
//var userClaims = new List<Claim>
//{
// new Claim(ClaimTypes.Name, user.UserName)
//};
User currentUser = _context.Users.FirstOrDefault(u => u.Logon.Equals(model.Username, StringComparison.CurrentCultureIgnoreCase));
if (currentUser != null)
{
var userRolesNames = _context.Roles.Join(_context.UserRoles.Where(p => p.UserId == currentUser.Id), roles => roles.Id, userRoles => userRoles.RoleId, (roles, userRoles) => roles).Select(roles => roles.Name).ToList();
await _signInManager.SignInAsync(currentUser, userRolesNames);
return Redirect("/Home/Index");
}
List<string> rolesList = null;
//var principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "Identity.Application"));
await _signInManager.SignInAsync(currentUser, rolesList);
return Redirect("/Home/Index");
}
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
}
}
return View(model);
}
[Authorize(Roles = "Admin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task SignOut()
{
await MyCustomSignOut("/Home/Index");
}
public async Task MyCustomSignOut(string redirectUri)
{
// inject the HttpContextAccessor to get "context"
await _signInManager.SignOutAsync();
var prop = new AuthenticationProperties()
{
RedirectUri = redirectUri
};
// after signout this will redirect to your provided target
await _httpContextAccessor.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme, prop);
}
}
_LoginPartial
<ul class="navbar-nav">
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a>@User.Identity.Name</a>
</li>
<li class="nav-item">
<form method="post" asp-controller="UserAccounts" asp-action="SignOut">
<input type="submit" class="btn btn-primary" value="Logout" />
</form>
</li>
}
else
{
<li class="dropdown nav-item">
<a asp-controller="UserAccounts" asp-action="Login">Login</a>
</li>
}
【问题讨论】:
-
这真的是 LDAP 吗?我没有看到任何 LDAP 配置的迹象,并且您的身份似乎存储在自定义数据库中,而不是从 LDAP 中检索。我真的希望这就是 LDAP 所需要的一切......
标签: c# asp.net asp.net-core ldap asp.net-identity