I have taken code from a previous custom Authorization attribute and come up with this:
public class PortalAuthorizeAttribute : AuthorizeAttribute
{
private WebSiteSession m_UserSession;
protected WebSiteSession myUserSession
{
get
{
if (m_UserSession == null)
try { m_UserSession = (WebSiteSession)HttpContext.Current.Session["UserSession"]; }
catch
{
m_UserSession = new WebSiteSession();
HttpContext.Current.Session["UserSession"] = m_UserSession;
}
return m_UserSession;
}
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.Result is HttpUnauthorizedResult || myUserSession == null || !myUserSession.IsAuthenticated || myUserSession.AdvertiserId == 0)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "client", filterContext.RouteData.Values["client"] },
{ "controller", "Account" },
{ "action", "Login" },
{ "returnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
}
I am working from within a larger project so we get our session from a higher namespace. The issue it will redirect fine if I am logged out or if I do not have authorization (redirect to the area login page) but it seems if I idle (session times out??) it will still act like I am authorized but will not have any credentials attached to the session. So it still thinks I am validly logged in but I am not. Am I forgetting something in my filter check? The cookie is no longer valid but its like the user is still able to access the page.
Thanks
The problem with your code stems from the fact that ASP.NET MVC 3 might cache instances of action filters. It is one of the breaking changes:
And since you have cached the
m_UserSessionprivate field into the action filter, it’s never null and your test doesn’t pass.So, here’s how you could proceed:
As far as creating and storing a new
WebSiteSessioninstance into the session, that’s not something that an authorization filter should do. It’s something that you should do inside yourLoginaction upon successful authentication. The authorization filter is there to only check if the user is authorized to access the action.