Jas*_*tol 6 c# authentication active-directory asp.net-mvc-4 simplemembership
我正在构建一个可以通过两种方式访问的Web应用程序.与我在同一组织中工作的每个人都可以使用我们的活动目录来访问该应用程序.
来自外部的每个人都应通过单独的会员数据库加入申请.每个人都应该在会员数据库中拥有他的角色,因此广告连接只是为了更容易记住密码和用户名.我搜索了互联网,但找不到类似的情况.这是我第一次使用广告.
有没有人知道可以使用的框架或者给我一个如何尝试解决问题的提示?
目前我实现了会员连接,System.Web.WebData.SimpleMembershipProvider并且工作正常.
在应用程序的后期开发中,我还需要一些其他的广告连接来检查一些信息,但这只是另一天的问题.
谢谢您的帮助.
打开你的web.config.
首先,您需要为ActiveDirectory提供connectionString:
<connectionStrings>
...
<add name="ADConnectionString" connectionString=LDAP://*adserver*/DC=*domain* />
...
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)
向下滚动到<membership>标签.确保为此设置了defaultProvider属性<membership>,例如:
<membership defaultProvider="SimpleMembershipProvider">
然后为AD成员添加新的提供者<providers>:
<add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
Run Code Online (Sandbox Code Playgroud)
这应该是web.config的技巧.现在我们需要在登录时授权AD用户.转到您的AccountController登录操作.首先我们尝试通过ActiveDirectory对用户进行身份验证,PrincipalContext在System.DirectoryServices.AccountManagement命名空间中有一个方便的类.如果失败,我们使用默认会员提供者:
public ActionResult Login(LoginModel model, string returnUrl)
{
try
{
// try to auth user via AD
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
if (pc.ValidateCredentials(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
}
// try the default membership auth if active directory fails
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Login failed");
}
}
catch
{
}
GetErrorsFromModelState();
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
对于以后的要求,您可以使用UserPrincipal类获取当前登录的ActiveDirectory用户:
using (var context = new PrincipalContext( ContextType.Domain))
{
using (var aduser = UserPrincipal.FindByIdentity( context,IdentityType.SamAccountName, HttpContext.User.Identity.Name))
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助,我没有错过任何东西.
| 归档时间: |
|
| 查看次数: |
7268 次 |
| 最近记录: |