要使用Active Directory进行身份验证的标识表单认证,可以按照以下步骤进行操作:
Microsoft.AspNet.Identity
和Microsoft.Owin.Security.ActiveDirectory
包。可以通过NuGet包管理器控制台安装这两个包,命令如下:
Install-Package Microsoft.AspNet.Identity
Install-Package Microsoft.Owin.Security.ActiveDirectory
Startup.cs
文件中进行配置。using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
[assembly: OwinStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseActiveDirectoryFederationServicesBearerAuthentication(
new ActiveDirectoryFederationServicesBearerAuthenticationOptions
{
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudience = "your-audience",
ValidIssuer = "your-issuer",
IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) =>
{
var store = new System.IdentityModel.Tokens.Jwt.Jwks.InMemorySymmetricSecurityKeyStore();
var securityKey = store.RetrieveSigningKey(identifier);
return new[] { securityKey };
}
},
AuthenticationType = "your-authentication-type"
});
}
}
}
在上面的代码中,需要根据实际情况修改ValidAudience
,ValidIssuer
和AuthenticationType
。
Web.config
文件中进行配置。
通过上述配置,将ASP.NET的表单认证和FormsAuthentication模块禁用。
AccountController
。using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;
public class AccountController : Controller
{
private IAuthenticationManager AuthenticationManager
{
get { return HttpContext.GetOwinContext().Authentication; }
}
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
// 在此处进行Active Directory身份认证
// 如果认证成功,使用以下代码进行登录
var claims = new[]
{
new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "username")
};
var identity = new System.Security.Claims.ClaimsIdentity(claims, "your-authentication-type");
AuthenticationManager.SignIn(identity);
return Redirect(returnUrl);
}
public ActionResult Logout()
{
AuthenticationManager.SignOut("your-authentication-type");
return RedirectToAction("Index", "Home");
}
}
在上面的代码中,可以在Login
方法中进行Active Directory身份验证,并使用AuthenticationManager.SignIn
方法进行登录。
HomeController
用于测试身份验证。using System.Web.Mvc;
using Microsoft.AspNet.Identity;
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
var username = User.Identity.GetUserName();
ViewBag.Username = username;
return View();
}
}
在上面的代码中,可以通过User.Identity.GetUserName
方法获取登录用户的用户名。
Views/Account/Login.cshtml
。@{
ViewBag.Title = "Login";
}
Login
@using (Html.BeginForm())
{
@Html.Label("Username:")
@Html.TextBox("", "", new { @class = "form-control" })
@Html.Label("Password:")
@Html.Password("", "", new { @class = "form-control" })
}
在上面的代码中,可以根据实际情况添加用户名和密码输入框。
Views/Home/Index.cshtml
。@{
ViewBag.Title = "Home";
}
Welcome, @ViewBag.Username
上一篇:ASP.NET MVC 5 - Razor 视图:通过不同的子元素筛选父元素
下一篇:ASP.NET MVC 5 - 使用ajax将视图模型数组发送到控制器(可选包含__RequestVerificationToken)