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

标签 c# asp.net asp.net-core ldap asp.net-identity

我已经设置了我的应用程序,它使用 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/

相关文章:

时间:2019-05-17 标签:c#asp.netidentityandcustomroles

c# - 在 WP7 应用程序中使用 .GIF 动画作为启动画面

mysql - 如何显示数据库获取的链接中的图像

c# - Swagger/NSwag : Redefine Parameter Type

c# - 带有 IIS 6 的 MVC

asp.net - WebControl创建中的Render和RenderControl有什么区别?

asp.net-core - 在 Asp.Net Core Web Api 中验证 B2C JWT token

c# - 调整浏览器窗口大小时如何停止页面刷新(跳转)?

c# - 如果在服务器端设置了控件的属性,则阻止或绕过事件

c# - 如何通过运行时嵌入表单切换来实现a-form-inside-a-form?