在选择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") ?? ;
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
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 域登录 (转载)的更多相关文章

  1. ASP.NET Core AD 域登录

    在选择AD登录时,其实可以直接选择 Windows 授权,不过因为有些网站需要的是LDAP获取信息进行授权,而非直接依赖Web Server自带的Windows 授权功能. 当然如果使用的是Azure ...

  2. AD域登录验证

    AD域登录验证 作者:Grey 原文地址:http://www.cnblogs.com/greyzeng/p/5799699.html 需求 系统在登录的时候,需要根据用户名和密码验证连接域服务器进行 ...

  3. Asp.net Core 跨域配置

    一般情况WebApi都是跨域请求,没有设置跨域一般会报以下错误 No 'Access-Control-Allow-Origin' header is present on the requested ...

  4. Asp.Net Core跨域配置

    在没有设置跨域配置的时候,Ajax请求时会报以下错误 已拦截跨源请求:同源策略禁止读取位于 http://localhost:5000/Home/gettime 的远程资源.(原因:CORS 头缺少 ...

  5. 跨平台运行ASP.NET Core 1.0(转载)

    前言 首先提一下微软更名后的叫法: ASP.NET 5 更名为 ASP.NET Core 1.0 .NET Core 更名为 .NET Core 1.0 Entity Framework 7 更名为  ...

  6. asp.net core后台系统登录的快速构建

    登录流程图 示例预览 构建步骤 当然,你也可以直接之前前往coding仓库查看源码,要是发现bug记得提醒我啊~ LoginDemo地址 1. 首先你得有一个项目 2. 然后你需要一个登录页面 完整L ...

  7. [转]ASP.NET Core集成微信登录

    本文转自:http://www.cnblogs.com/early-moon/p/5819760.html 工具: Visual Studio 2015 update 3 Asp.Net Core 1 ...

  8. ASP.NET Core集成微信登录

    工具: Visual Studio 2015 update 3 Asp.Net Core 1.0 1 准备工作 申请微信公众平台接口测试帐号,申请网址:(http://mp.weixin.qq.com ...

  9. 配置visual studio code进行asp.net core rc2的开发(转载jeffreywu)

    1.安装.net core sdk https://github.com/dotnet/cli#installers-and-binaries,根据你的系统选择下载 2.下载vscode的C#扩展插件 ...

随机推荐

  1. js延迟加载优化页面响应速度

    网页打开速度是衡量网站性能的一个极为重要的指标,今天就来说说如何通过JS延迟加载的方式提高页面响应速度: JS延迟加载的 含义:即等页面加载完成之后再加载 JavaScript 文件.作用:JS延迟加 ...

  2. 第十五章——自编码器(Autoencoders)

    自编码器是一种能够通过无监督学习,学到输入数据高效表示的人工神经网络.输入数据的这一高效表示称为编码(codings),其维度一般远小于输入数据,使得自编码器可用于降维(查看第八章).更重要的是,自编 ...

  3. JAVA后台框架优化之日志篇

    1.日志规范 各业务系统日志需要统一,以方便查看.收集日志, 日后统一ELK日志管理,以下为项目的日志配置, 这是兼容当前系统的日志,以后推行微服架构时会有变动,但日志存放方式不会改变,日后会推行sp ...

  4. 使用自定义视图的AlertDialog

    使用自定义视图的AlertDialog主要分为以下几个步骤: 1)利用XML文件构建自己的的视图 2)将视图添加到AlertDialog中 * 在进行第二步之前,有时需要对对话框窗口进行额外的设置 下 ...

  5. Oracle replace()函数

    往Oracle 中导入数据时,有一个列导入的数据应该时‘2017-04-17’ 的格式,结果导入的数据为 ‘2017/04/17’格式的,1000多条记录要一条条改基本不可能. 于是想到了replac ...

  6. [翻译] ATTutorialController

    ATTutorialController https://github.com/AfonsoTsukamoto/ATTutorialController A simple to use tutoria ...

  7. 在oracle电子商务套件中输出信息

    一.用自定义用户HAND_SL登陆http://zd01.haasgz.hand-china.com:30000/ 添加可执行并发程序 执行文件名填写自己的包名称.入口函数/过程名 二.将可执行程序添 ...

  8. 沉淀再出发:xml的意义和存在的价值

    沉淀再出发:xml的意义和存在的价值 一.前言 学习了那么多的语言.框架.语法和基础知识,我们对于数据的理解或许有了一定的认识,但是如何描述.包装.传输.存储数据的手法和流程我们了解的或许并不多,其中 ...

  9. ZT 理解class.forName()

    理解class.forName() 分类: [Java SE 基础] 2012-05-17 07:53 3892人阅读 评论(3) 收藏 举报 classloaderclassjdbcejb数据库 目 ...

  10. 关于 MapReduce

    继续摘抄<Hadoop 权威指南>第二章,跳过不少于我复杂的东西,但依然是捉急的效率,开始觉得看不完另外一本全英文的书,大概每天要看5页吧... 以上. MapReduce 是一种可用于数 ...