簡體   English   中英

帶有 LDAP 身份驗證的 Asp.Net Core 2.1 身份

[英]Asp.Net Core 2.1 Identity with LDAP authentication

我已經設置了我的應用程序,它使用身份在站點上進行角色訪問。

我正在從使用自定義聲明轉換器的 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);
    }
}

_登錄部分

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

出於某種原因,我不得不聲明所有各種身份驗證方案選項,即使它們在我的應用程序中都是相同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM