我已经设置了应用程序,该应用程序使用Identity来访问网站上的角色。
我正在从具有自定义声明转换器的Windows身份验证切换到使用LDAP,以便用户将拥有一个登录页面,而不像chrome中弹出的Windows身份验证类似“ javascript警报”。
问题是,即使我在LDAP中找到要登录的用户以及在应用程序中找到具有角色的用户,它仍然无法登录。 SignInAsync函数执行没有任何问题,但在重定向上仍然显示未登录。CookieAuthentication Setup是否有问题或我错了? _LoginPartial仍然显示“登录”。
我当前的设置是:
ConfigureServices
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();
自定义SignInManager
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>
}
答案 0 :(得分:0)
多数代码是正确的。 我唯一需要做的修改是以下内容。
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = new PathString("/UserAccounts/Login");
options.AccessDeniedPath = new PathString("/UserAccounts/AccessDenied");
});
由于某些原因,我不得不声明所有各种身份验证方案选项,即使它们在我的应用程序中都相同。