網站首頁 編程語言 正文
在選擇AD登錄時,其實可以直接選擇 Windows 授權,不過因為有些網站需要的是LDAP獲取信息進行授權,而非直接依賴Web Server自帶的Windows 授權功能。
當然如果使用的是Azure AD/企業(yè)賬號登錄時,直接在ASP.NET Core創(chuàng)建項目時選擇就好了。
來個ABC:
新建一個ASP.NET Core項目
Nuget引用dependencies / 修改```project.json```
Novell.Directory.Ldap.NETStandard
Microsoft.AspNetCore.Authentication.Cookies
版本如下:
"Novell.Directory.Ldap.NETStandard": "2.3.5",
"Microsoft.AspNetCore.Authentication.Cookies": "1.1.0"
本文的AD登錄使用的是第三方的
```Novell.Directory.Ldap.NETStandard``` 進行的LDAP操作(還沒有看這個LDAP的庫是否有安全性問題,如果有需要修改或更換)
建立一個LDAP操作的工具類
代碼在下面鏈接中,就不單獨貼了,基本上就2個方法:
Register是獲取基本配置信息的
Validate是來驗證用戶名密碼的
using System; using Microsoft.Extensions.Configuration; using Novell.Directory.Ldap; namespace Demo { public class LDAPUtil { public static string Host { get; private set; } public static string BindDN { get; private set; } public static string BindPassword { get; private set; } public static int Port { get; private set; } public static string BaseDC { get; private set; } public static string CookieName { get; private set; } public static void Register(IConfigurationRoot configuration) { Host = configuration.GetValue("LDAPServer"); Port = configuration?.GetValue ("LDAPPort") ?? 389; BindDN = configuration.GetValue ("BindDN"); BindPassword = configuration.GetValue ("BindPassword"); BaseDC = configuration.GetValue ("LDAPBaseDC"); CookieName = configuration.GetValue ("CookieName"); } public static bool Validate(string username, string password) { try { using (var conn = new LdapConnection()) { conn.Connect(Host, Port); conn.Bind($"{BindDN},{BaseDC}", BindPassword); var entities = conn.Search(BaseDC,LdapConnection.SCOPE_SUB, $"(sAMAccountName={username})", new string[] { "sAMAccountName" }, false); string userDn = null; while (entities.hasMore()) { var entity = entities.next(); var account = entity.getAttribute("sAMAccountName"); //If you need to Case insensitive, please modify the below code. if (account != null && account.StringValue == username) { userDn = entity.DN; break; } } if (string.IsNullOrWhiteSpace(userDn)) return false; conn.Bind(userDn, password); // LdapAttribute passwordAttr = new LdapAttribute("userPassword", password); // var compareResult = conn.Compare(userDn, passwordAttr); conn.Disconnect(); return true; } } catch (LdapException) { return false; } catch (Exception) { return false; } } } }
在applicationSettings.json中添加基本的域配置
"LDAPServer
": "192.168.1.1",//域服務器
"LDAPPort
": 389,//端口,一般默認就是這個
"CookieName
": "testcookiename",//使用Cookie登錄的Cookie的Key
"BindDN
": "CN=DoWebUser,CN=Users",//用來獲取LDAP的信息用戶的用戶名
"BindPassword
": "!DoWebUserPassword",//用來獲取LDAP的信息的用戶的密碼,即DoWebUser的密碼
"LDAPBaseDC
": "DC=aspnet,DC=com",//域的DC
Startup.cs中修改
Startup方法中:
LDAPUtil.Register(Configuration);
ConfigureServices 方法中:
services.AddAuthorization(options =>{});
Configure方法中:
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = Configuration.GetValue("CookieName"), LoginPath = new PathString("/Account/Login/"), AccessDeniedPath = new PathString("/Account/Login/"), AutomaticAuthenticate = true, AutomaticChallenge = true });
AccountController中添加登錄和注銷的Action
登錄的頁面:
[AllowAnonymous] public IActionResult Login() { return View(); }
登錄的Post頁面:
[HttpPost] [AllowAnonymous] public async TaskLogin(string u, string p) { if (LDAPUtil.Validate(u, p)) { var identity = new ClaimsIdentity(new MyIdentity(u));//這個MyIdentity只是一個祼的IIdentity的實現的類 var principal = new ClaimsPrincipal(identity); await HttpContext.Authentication.SignInAsync(LDAPUtil.CookieName, principal); return RedirectToAction("Index", "Home"); } return View(); }
注銷的頁面:
[Authorize] public async TaskLogout() { await HttpContext.Authentication.SignOutAsync(LDAPUtil.CookieName); return RedirectToAction("Index", "Home"); }
Demo
https://github.com/chsword/aspnet-core-ad-authentication
引用
https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard
https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.Cookies/
原文鏈接:https://www.cnblogs.com/chsword/p/aspnet-core-ad-auth.html
相關推薦
- 2022-12-03 Go?語言單例模式示例詳解_Golang
- 2022-10-26 Python如何用NumPy讀取和保存點云數據_python
- 2022-04-30 C語言鏈表實現銷售管理系統(tǒng)_C 語言
- 2022-12-06 React.memo?和?useMemo?的使用問題小結_React
- 2022-07-07 圖解AVL樹數據結構輸入與輸出及實現示例_C 語言
- 2022-08-19 python中的函數和變量的用法
- 2022-04-11 C++實現簡單的計算器小功能_C 語言
- 2022-02-10 Linux高并發(fā)踩過的坑及性能優(yōu)化介紹_Linux
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支