我在 2 个 MVC 站点(称为 SiteA 和 SiteB)上进行了基本的单点登录,使用的方法类似于以下方法:
http://forums.asp.net/p/1023838/2614630.aspx
它们位于同一域的子域上,并在 web.config 中共享哈希\加密密钥等。我已经修改了 cookie,因此同一域上的所有站点都可以访问它。所有这些似乎工作正常。
这些站点位于不同的服务器上,无法访问相同的 SQL 数据库,因此只有 SiteA 实际保存用户登录详细信息。SiteB 有一个成员数据库,但用户为空。
这适用于我所需的场景,即:
1) 用户登录 SiteA
2) 应用程序从 SiteA(通过 AJAX)和 SiteB(通过 AJAX 使用 JSONP)加载数据
我在 SiteA 的 AccountController 上有以下登录操作,这是“魔术”发生的地方:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
//modify the Domain attribute of the cookie to the second level of domain
// Add roles
string[] roles = Roles.GetRolesForUser(model.UserName);
HttpCookie cookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, false);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
// Store roles inside the Forms cookie.
FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(ticket.Version, model.UserName,
ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, String.Join("|", roles), ticket.CookiePath);
cookie.Value = FormsAuthentication.Encrypt(newticket);
cookie.HttpOnly = false;
cookie.Domain = ConfigurationManager.AppSettings["Level2DomainName"];
Response.Cookies.Remove(cookie.Name);
Response.AppendCookie(cookie);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
这做了一些我在初始场景中并不严格需要的东西,但与我的问题有关。它将登录到 SiteA 的用户的角色列表插入到身份验证票证的 UserData 中。然后通过 global.asax 中的以下内容在 SiteB 上“恢复”:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (Context.Request.IsAuthenticated)
{
FormsIdentity ident = (FormsIdentity) Context.User.Identity;
string[] arrRoles = ident.Ticket.UserData.Split(new[] {'|'});
Context.User = new System.Security.Principal.GenericPrincipal(ident, arrRoles);
}
}
在我将角色添加到组合中之前,上述所有内容都有效。如果我只用 [Authorize] 属性装饰 SiteB 上的 Controllers\Actions,一切都会正常工作。但是一旦我添加 [Authorize(roles="TestAdmin")] 用户就不能再访问该控制器操作。显然我已将用户添加到 TestAdmin 角色。
如果我在 SiteB 上调试 global.asax 代码,当我离开 global.asax 代码时它看起来没问题,但是当我在控制器本身中遇到断点时,Controller.User 和 Controller.HttpContext.User 现在是一个系统。 Web.Security.RolePrincipal 不再设置角色。
所以我的问题是:有人知道我如何恢复 SiteB 上的角色或其他方式吗?