標籤:test 添加 伺服器 頁面 scheme win configure sid tin
在選擇AD登入時,其實可以直接選擇 Windows 授權,不過因為有些網站需要的是LDAP擷取資訊進行授權,而非直接依賴Web Server內建的Windows 授權功能。
當然如果使用的是Azure AD/企業帳號登入時,直接在ASP.NET Core建立項目時選擇就好了。
來個ABC:
1.建立一個ASP.NET Core項目
2.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的庫是否有安全性問題,如果有需要修改或更換)
3.建立一個LDAP操作的工具類
代碼在下面連結中,就不單獨貼了,基本上就2個方法:
Register是擷取基本配置資訊的
Validate是來驗證使用者名稱密碼的
https://github.com/chsword/aspnet-core-ad-authentication/blob/master/src/Demo/LDAPUtil.cs
4.在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
5.Startup.cs中修改
Startup方法中:
LDAPUtil.Register(Configuration);
ConfigureServices 方法中:
services.AddAuthorization(options =>{});
Configure方法中:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = Configuration.GetValue<string>("CookieName"),
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/Login/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
6.AccountController中添加登入和登出的Action
登入的頁面:
[AllowAnonymous]
public IActionResult Login()
{
return View();
}
登入的Post頁面:
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(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 Task<IActionResult> Logout()
{
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/
ASP.NET Core AD 域登入