Question

I just need to make an manual autentication on MVC3 and the problem is, when the user access the url from project, i have this code on base class:

public class BaseController : Controller
{
    private Usuario loggedUser;
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        if (requestContext.HttpContext.Request.RawUrl != "/Home/Login")
        {
            if (requestContext.HttpContext.Session["usuario"] != null)
            {
                loggedUser = (Usuario)requestContext.HttpContext.Session["usuario"];
                ViewBag.nomeUsuario = loggedUser.Nome;
                ViewBag.idUsuario = loggedUser.Id;
            }
            else
            {
                requestContext.HttpContext.Response.RedirectPermanent("~/Home/Login");
            }
        }
        base.Initialize(requestContext);
    }

The problem is, when they are not authorized I send a redirect BUT the initialize continues to process the request action. I think the validation are on not a good place becouse I can remove the inicalize method.

Was it helpful?

Solution

Redirect does not work in this context. Try overriding OnAuthorization and return a RedirectResult.

Even better would be to implement this logic as an attribute.

public class MyAuthorize : AuthorizeAttribute
{
    private Usuario loggedUser;
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.RawUrl != "/Home/Login")
        {
            if (filterContext.HttpContext.Session["usuario"] != null)
            {
                loggedUser = (Usuario) filterContext.HttpContext.Session["usuario"];
                ViewBag.nomeUsuario = loggedUser.Nome;
                ViewBag.idUsuario = loggedUser.Id;
            }
            else
            {
                filterContext.Result = new RedirectResult("~/Home/Login");
            }
            base.OnAuthorization(filterContext);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top