簡體   English   中英

在 ASP.NET Core 3.1 中使用 windows 身份驗證進行授權

[英]Authorization with windows authentication in ASP.NET Core 3.1

據我了解,有一種方法可以檢索用戶所屬的組。 例如管理員、用戶等。

之后,我想將其轉化為索賠。 我找不到如何檢索用戶組。

目前我正在使用我的本地用戶而不是(域 Active Directory)。

這個問題有解決方案嗎?

這是一種好方法還是更好地從數據庫中檢索每個用戶的權限然后使用它們進行操作?

您需要知道的是 AD 僅在windows 主機上工作。 在開始項目之前閱讀Microsoft 文檔

添加啟動配置,創建登錄頁面

services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
             .AddCookie(options =>
             {
                options.LoginPath = "/Login";
             });
.....

app.UseAuthentication();
app.UseAuthorization();

第三你的需求:

  1. 您的 AD 域:yourdomain.com
  2. 您的 ldap url 示例: LDAP://DC.yourdomain.Z4D236D9A2D102C5FE6AD1C50
  3. 關於ldap 查詢字符串的一些知識

application.json 配置:

"ldap": {
    "path": "LDAP://DC.yourdomain.com",
    "domain": "yourdomain.com",
    "personFilter": "(SAMAccountName={username})",
    "groupFilter": "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
    //"property": "cn,displayName,mail,givenName,sn,o,title,company,department,telephoneNumber,description,userPrincipalName",
    "property": "cn,displayName,mail,givenName,sn,o,title,company,department"
    //"property": "cn,member,memberof,sAMAccountName,primaryGroupToken"
}

您可以使用此方法檢查用戶名和密碼

public Dictionary<string, string> UserInfo { get; private set; }
public bool IsAuthenticated(string username, string password)
        {
            bool result = false;


            string domainAndUsername = Configuration["ldap:domain"] + @"\" + username;
            DirectoryEntry entry = new DirectoryEntry(Configuration["ldap:path"], domainAndUsername, password);
            try
            {
                Object obj = entry.NativeObject;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = Configuration["ldap:personFilter"].Replace("{username}", username);

                var propList = Configuration["ldap:property"].Split(',');
                search.PropertiesToLoad.AddRange(propList);

                SearchResult searchResult = search.FindOne();
                if (null == searchResult)
                {
                    return false;
                }

                foreach (var propName in propList)
                {
                    UserInfo.Add(propName, GetProperty(searchResult.Properties, propName));
                }

                DirectoryEntry obUser = new DirectoryEntry(searchResult.Path);
                object obGroups = obUser.Invoke("Groups");
                var groupList = new List<string>();
                foreach (object ob in (IEnumerable)obGroups)
                {
                    DirectoryEntry obGpEntry = new DirectoryEntry(ob);
                    groupList.Add(obGpEntry.Name);
                }

                UserInfo.Add("group", string.Join(",", groupList));
                result = true;
            }
            catch (Exception ex)
            {
                throw new SysAuthException("Invalid Authentication", ex);
            }

            return result;
        }

登錄成功時,您可以從 userInfo 屬性中檢查所有用戶信息

登錄頁面的示例代碼(將聲明和登錄 state 添加到 net core 管道):

    try
            {
                if (Authentication.IsAuthenticated(UserData.Username, UserData.Password))
                {
                    var claims = new List<Claim>() {
                        new Claim(ClaimTypes.Name, UserData.Username)
                    };

                    foreach (var item in Authentication.UserInfo)
                    {
                        claims.Add(new Claim(item.Key, item.Value));
                    }

                    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var principal = new ClaimsPrincipal(identity);

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties()
                    {
                        IsPersistent = UserData.RememberLogin
                    });

                    if (!string.IsNullOrEmpty(UserData.ReturnUrl))
                        return LocalRedirect(UserData.ReturnUrl);
                    return Redirect("/");
                }
            }
            catch (SysAuthException ex)
            {
                Error = ex.InnerException.Message;
            }

如果您需要保護您的頁面,請在頁面頂部添加@attribute [Authorize] ,您還可以檢查其他聲明,例如具有此屬性的角色或組

示例代碼顯示當前用戶信息

    <div>
    <table class="table table-bordered table-striped">
        <caption>Current User Info</caption>
        @foreach (var claim in User.Claims)
        {
            <tr><td>@claim.Type</td><td>@claim.Value</td></tr>
        }
    </table>
</div>

暫無
暫無

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

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