在选择 AD 登录时, 其实可以直接选择 Windows 授权, 不过因为有些网站需要的是 LDAP 获取信息进行授权, 而非直接依赖 web Server 自带的 Windows 授权功能.
当然如果使用的是 Azure AD / 企业账号登录时, 直接在 ASP.NET Core 创建项目时选择就好了.
来个 ABC:
1. 新建一个 ASP.NET Core 项目 ABC
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 是来验证用户名密码的
- 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;
- }
- }
- }
- }
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
引用
来源: http://www.bubuko.com/infodetail-2846532.html