gpt4 book ai didi

c# - 具有 LDAP 身份验证的 Asp.Net Core 2.1 身份

转载 作者:太空宇宙 更新时间:2023-11-03 12:04:24 26 4
gpt4 key购买 nike

我已经设置了我的应用程序,它使用 Identity 在网站上进行角色访问。

我正在从使用自定义声明转换器的 Windows 身份验证切换到使用 LDAP,这样用户将拥有一个登录页面,这与 chrome 中弹出的“类似 javascript 警报”的 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>

}

最佳答案

大部分代码都是正确的。我唯一需要做的修改如下。

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");
});

出于某种原因,我不得不声明所有各种身份验证方案选项,即使它们在我的应用程序中都是相同的。

关于c# - 具有 LDAP 身份验证的 Asp.Net Core 2.1 身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com