ASP.NET的Core AD域登錄過程示例
在選擇AD登錄時(shí),其實(shí)可以直接選擇 Windows 授權(quán),不過因?yàn)橛行┚W(wǎng)站需要的是LDAP獲取信息進(jìn)行授權(quán),而非直接依賴Web Server自帶的Windows 授權(quán)功能。
當(dāng)然如果使用的是Azure AD/企業(yè)賬號(hào)登錄時(shí),直接在ASP.NET Core創(chuàng)建項(xiàng)目時(shí)選擇就好了。
來個(gè)ABC:
新建一個(gè)ASP.NET Core項(xiàng)目
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``` 進(jìn)行的LDAP操作(還沒有看這個(gè)LDAP的庫是否有安全性問題,如果有需要修改或更換)
建立一個(gè)LDAP操作的工具類
代碼在下面鏈接中,就不單獨(dú)貼了,基本上就2個(gè)方法:
Register是獲取基本配置信息的
Validate是來驗(yàn)證用戶名密碼的
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<string>("LDAPServer");
Port = configuration?.GetValue<int>("LDAPPort") ?? 389;
BindDN = configuration.GetValue<string>("BindDN");
BindPassword = configuration.GetValue<string>("BindPassword");
BaseDC = configuration.GetValue<string>("LDAPBaseDC");
CookieName = configuration.GetValue<string>("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",//域服務(wù)器
"LDAPPort": 389,//端口,一般默認(rèn)就是這個(gè)
"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<string>("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 Task<IActionResult> Login(string u, string p)
{
if (LDAPUtil.Validate(u, p))
{
var identity = new ClaimsIdentity(new MyIdentity(u));//這個(gè)MyIdentity只是一個(gè)祼的IIdentity的實(shí)現(xiàn)的類
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域登錄過程示例的詳細(xì)內(nèi)容,更多關(guān)于ASP.NET Core AD域登錄的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用Asp.net Mvc3 Razor視圖方式擴(kuò)展JQuery UI Widgets方法介紹
jquery easyui grid或者extjs grid,jtable的代碼非常簡潔、對于grid功能要求不是很復(fù)雜的情況下,強(qiáng)烈推薦大家使用2012-11-11
為什么ASP.NET Core 數(shù)據(jù)庫連接串的值和appsettings.json配的不一樣?
這篇文章主要介紹了為什么數(shù)據(jù)庫連接串的值和appsettings.json配的不一樣?下面我們就帶著疑問閱讀下文,需要的小伙伴可以參考一下,希望對你有所幫助2022-02-02
ASP.NET webUploader上傳大視頻文件相關(guān)web.config配置
本文主要介紹了webUploader上傳大視頻文件相關(guān)web.config的配置。具有一定的參考價(jià)值,下面跟著小編一起來看下吧2017-01-01
認(rèn)識(shí)ASP.NET配置文件Web.config
Web.config文件是一個(gè)XML文本文件,它用來儲(chǔ)存 ASP.NET Web 應(yīng)用程序的配置信息(如最常用的設(shè)置ASP.NET Web 應(yīng)用程序的身份驗(yàn)證方式),它可以出現(xiàn)在應(yīng)用程序的每一個(gè)目錄中2006-07-07
ASP.NET Core 中間件的使用之全局異常處理機(jī)制
我們今天這篇文章就來說說代碼異常問題怎么快速定位,減少不必要的時(shí)間浪費(fèi)。異常是一種運(yùn)行時(shí)錯(cuò)誤,當(dāng)異常沒有得到適當(dāng)?shù)奶幚恚芸赡軙?huì)導(dǎo)致你的程序意外終止。下面雄安邊將詳細(xì)介紹,需要的朋友可以參考下2021-09-09

