我有一个非常奇怪的场景,我被困住了。我有一个 ASP.Net MVC 4 应用程序,我在其中对用户进行身份验证并创建一个 authCookie 并将其添加到响应的 cookie 中,然后将它们重定向到目标页面:
if (ModelState.IsValid)
{
var userAuthenticated = UserInfo.AuthenticateUser(model.UserName, model.Password);
if (userAuthenticated)
{
var userInfo = UserInfo.FindByUserName(model.UserName);
//SERIALIZE AUTHENTICATED USER
var serializer = new JavaScriptSerializer();
var serializedUser = serializer.Serialize(userInfo);
var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), false, serializedUser);
var hash = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash) {Expires = ticket.Expiration};
Response.Cookies.Add(authCookie);
if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/") && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\"))
{
return Redirect(model.ReturnUrl);
}
var url = Url.Action("Index", "Course");
return Redirect(url);
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
这在所有浏览器中都可以正常工作。我可以登录并访问我的应用程序中的安全页面。
我的客户正在请求此应用程序的 android 版本。所以,我想弄清楚如何将此应用程序转换为 APK 文件。我的第一次尝试是创建一个简单的 index.html 页面,其中包含一个以应用程序为目标的 iframe。这在 Firefox 和 IE 9 中运行良好。但是,当通过 Chrome 访问包含指向应用程序的 iframe 的 index.html 页面时,我通过了上面的登录代码,用户被重定向到安全控制器,但是安全控制器有一个自定义属性来确保用户通过身份验证:
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated) return;
if (filterContext.HttpContext.Request.Url == null) return;
var returnUrl = filterContext.HttpContext.Request.Url.AbsolutePath;
if (!filterContext.HttpContext.Request.Browser.IsMobileDevice)
{
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + string.Format("?ReturnUrl={0}", returnUrl), true);
}
else
{
filterContext.HttpContext.Response.Redirect("/Home/Home", true);
}
}
}
我的应用程序失败:filterContext.HttpContext.User.Identity.IsAuthenticated。IsAuthenticated 始终为 false,即使用户已在上面的代码中进行了身份验证。
请记住,这只发生在通过 Chrome 中的 iframe 访问应用程序时。如果我直接访问应用程序而不是通过 iframe,那么一切正常。
有任何想法吗?
更新:
我的控制器扩展了 SecureController。在 SecureController 的构造函数中,我有反序列化用户的代码:
public SecureController()
{
var context = new HttpContextWrapper(System.Web.HttpContext.Current);
if (context.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
var serializer = new JavaScriptSerializer();
var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
var ticket = FormsAuthentication.Decrypt(cookie);
CurrentUser = serializer.Deserialize<UserInfo>(ticket.UserData);
}
else
{
CurrentUser = new UserInfo();
}
//if ajax request and session has expired, then force re-login
if (context.Request.IsAjaxRequest() && context.Request.IsAuthenticated == false)
{
context.Response.Clear();
context.Response.StatusCode = 401;
context.Response.Flush();
}
}