我有一个MVC应用程序,它是一个API文档站点,位于表单auth之后。该站点中只有两个页面... home,列出(在较高级别)站点上的所有端点,如以及数据对象。您可以单击这些数据对象/端点中的任何一个,然后转到详细信息页面。
我的每个页面都使用[Authorize(Roles="role,names,here")]
属性进行修饰。正如预期的那样,当您进入该站点时,您将被重定向到登录页面,并且任何后续请求都可以正常工作。
然而,昨天该网站开始表演,我不知道为什么。初次登录后,您请求的页面加载得很好。但是,只要您单击链接以导航到任何其他页面,用户就会被重定向到登录页面,并且凭据不再有效。
是否有任何想法导致这种情况,以及我如何解决这个问题?
[编辑] 我不知道为什么,但是我的sessionState配置在我的web.config中被注释掉了(我没有这样做,正如我所说,这是在48小时前工作),但它似乎没有注释这个修复它:
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="dbConn"/>
</providers>
</sessionState>
答案 0 :(得分:0)
最好向我们展示你的班级提供会话。但是使用这个: 你会有一个像这样的帐户控制器:
UserApplication userApp = new UserApplication();
SessionContext context = new SessionContext();
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(User user)
{
var authenticatedUser = userApp.GetByUsernameAndPassword(user);//you get the user from your application and repository here
if (authenticatedUser != null)
{
context.SetAuthenticationToken(authenticatedUser.UserId.ToString(),false, authenticatedUser);
return RedirectToAction("Index", "Home");
}
return View();
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
你的SessionContext将是这样的:
public class SessionContext
{
public void SetAuthenticationToken(string name, bool isPersistant, User userData)
{
string data = null;
if (userData != null)
data = new JavaScriptSerializer().Serialize(userData);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddYears(1), isPersistant, userData.UserId.ToString());
string cookieData = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieData)
{
HttpOnly = true,
Expires = ticket.Expiration
};
HttpContext.Current.Response.Cookies.Add(cookie);
}
public User GetUserData()
{
User userData = null;
try
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
userData = new JavaScriptSerializer().Deserialize(ticket.UserData, typeof(User)) as User;
}
}
catch (Exception ex)
{
}
return userData;
}
}