How to use session for authentication in MVC 4 with C #?

5

My scenario is as follows. I have an MVC 4 application. On my controller I check the logged in user and password. (I think) I put user data in a session after the data is verified and correct.

My pages are cshtml (Razor). And I have a master page that will use the Session data to show the logged in user for example.

If the login data is not correct, the session will be empty and I will redirect to the login page.

Questions:

  • How to open and close the session?
  • How to set the idle time to close it?
  • What it takes for the system to only allow direct access to the URLs after login and active session.

My login screen action after sending the data:

    [HttpPost]
    public ActionResult Index(UsuarioDTO dto)
    {
        UsuarioDTO ValidarLogin = null;

        UsuarioDTO usuario = new UsuarioDTO();
        usuario.Login = dto.Login;
        usuario.Senha = dto.Senha;

        negocio = new AeroJetNEGOCIO();

        try
        {
            ValidarLogin = negocio.Login.LogarUsuario(usuario);

            usuario = ValidarLogin;

            Session["usuarioLogado"] = usuario;                   

            return RedirectToAction("Index", "CadastroCliente");
        }
        catch (Exception e)
        {
            ViewBag.classe = "alert";
            ViewBag.msg = e.Message;
            return View();
        }
    }

OBS: This session that I include does not even know how it behaves. It was just an attempt.

This screen redirects to another Action from another Controller that is a screen for a user already logged in.

    public ActionResult Index()
    {
         return View();
    }

I do not know if I should put any code to validate the Session there. I need help with that part.

If you need the cshtml of the master page or the page that comes after the login I post.

    
asked by anonymous 02.07.2014 / 23:50

1 answer

4

Create a SessionManager

public static class SessionManager
{
    public static void RegisterSession(string key, object obj)
    {
        System.Web.HttpContext.Current.Session[key] = obj;
    }

    public static void FreeSession(string key)
    {
        System.Web.HttpContext.Current.Session[key] = null;
    }


    public static bool CheckSession(string key)
    {
        if (System.Web.HttpContext.Current.Session[key] != null)
            return true;
        else
            return false;
    }

    public static bool CheckSession(string key, System.Web.HttpContextBase contexto)
    {
        if (contexto.Session[key] != null)
            return true;
        else
            return false;
    }

    public static object ReturnSessionObject(string key)
    {
        if (CheckSession(key))
            return System.Web.HttpContext.Current.Session[key];
        else
            return null;
    }

    public static object ReturnSessionObject(string key, System.Web.HttpContextBase contexto)
    {
        if (CheckSession(key, contexto))
            return contexto.Session[key];
        else
            return null;
    }
}

Create a CustomAuthorizeAttribute

public struct SessionKeys
{
    public const string Usuario = "Usuario";
}

public class ResearchAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (SessionManager.CheckSession(SessionKeys.Usuario) == true)
            return true;
        else
            return false;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (SessionManager.CheckSession(SessionKeys.Usuario) == false)
        {
            filterContext.Result = new RedirectToRouteResult(
                            new RouteValueDictionary 
                    {
                        { "action", "Login" },
                        { "controller", "Research" }
                    });
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

Create a CustomAuthenticatedModelBinder

class ResearchAutenticadoModelBinder : IModelBinder
{
    public object GetValue(ControllerContext controllerContext)//, string modelName, Type modelType, ModelStateDictionary modelState)
    {
        var modelo = new ResearchAutenticadoBindModel();
        modelo.Usuario = SessionManager.ReturnSessionObject(SessionKeys.Usuario, controllerContext.HttpContext).ToString();
        return modelo;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext", "controllerContext is null.");
        if (bindingContext == null)
            throw new ArgumentNullException("bindingContext", "bindingContext is null.");

        return GetValue(controllerContext);
    }
}

Add your CustomModelBinder in Application_Start

ModelBinders.Binders.Add(typeof(ResearchAutenticadoBindModel), new ResearchAutenticadoModelBinder());

You can now sign in to the Controllers :

SessionManager.RegisterSession(SessionKeys.Usuario, "Usuario XYZ");

And you can use your Authorize in the restricted Actions :

    [ResearchAuthorize]
    public ActionResult New(ResearchAutenticadoBindModel login)
    {
        return Edit(login, 0);
    }
    
03.07.2014 / 00:18