使用ASP.NET Identity创建中央身份验证服务,用于身份验证并共享用户凭据。在两个分别的ASP.NET MVC应用程序中,配置以使用相同的中央身份验证服务进行身份验证。
例如,我们可以创建一个名为"CentralAuth"的ASP.NET Identity项目,并配置其作为中央身份验证服务。然后,在两个分别的ASP.NET MVC应用程序中,使用以下代码配置身份验证:
// 在Startup.Auth.cs文件中
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseCentralizedOAuth(new CentralizedOAuthOptions()){
AuthenticationMode = AuthenticationMode.Passive,
ClientId = "myAppId",
ClientSecret = "myAppSecret"
});
// 在Web.Config文件中
然后,在两个应用程序中定义UseCentralizedOAuth方法:
// 在Controllers/AccountController.cs文件中
public ActionResult ExternalLoginCallback(string returnUrl)
{
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
var loginInfo = authManager.GetExternalLoginInfoAsync().Result;
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var userManager = HttpContext.GetOwinContext().GetUserManager();
var user = userManager.FindAsync(loginInfo.Login).Result;
if (user != null)
{
authManager.SignIn(new AuthenticationProperties { IsPersistent = false }, user.GenerateUserIdentityAsync