在选择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/
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com