Contexts unique to authenticated users

4

Using the method recommended by @Gigano in this response ( Is it possible to leave connectionString dynamically? ), I was able to get a dynamic connection, and using the idea of mapping a context with the user data as the name of the bank, host, etc ... I encountered another problem: Each user logged in, the data contained in the context is overwritten by the data of the most recent authenticated user.

What is the elegant way of creating a context for each logged-in user on the system where there is no interference from the other?

Cookies? Sessions?

Update

The change of bank is made all the time the entity is called:

public EntidadesDCSystem(string str = "Conexao") : base(str)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            var user = HttpContext.Current.Session["usrProfile"] as UsuarioContexto;
            this.MudarBanco(database: user.database, configConnectionStringName: "Conexao");
        }
    }

I did so (with session), as it was the only way I found that user data would not merge. It follows where I set this session, which is the moment of user login.

[HttpPost]
    public ActionResult Login(AuthLogin form, string returnUrl)
    {
        ...

        //FormsAuthentication.SetAuthCookie(usr.nome, true);
        var userData = usr.descricao + '|' + usr.usuarioid;

        var ticket = new FormsAuthenticationTicket(1,
            usr.nome,
            DateTime.Now,
            DateTime.Now.AddHours(8),
            true,
            userData);

        var encTicket = FormsAuthentication.Encrypt(ticket);

        var userProfile = new UsuarioContexto
        {
            nome = usr.nome,
            userid = usr.usuarioid,
            database = usr.conexao
        };

        Session["usrProfile"] = userProfile;

        ...
    }
    
asked by anonymous 01.11.2016 / 19:18

1 answer

0
  

What is the elegant way of creating a context for each user logged in on the system where one does not interfere with the other?

     

Cookies? Sessions?

Cookies would be the best alternative. The data that characterizes each user is on their machines and the system identifies the correct connection per request.

On its implementation, Session has problems with load balancing. A suggestion using Cookies would be:

var meuCookie = new HttpCookie("MeuCookie");

meuCookie.Values["Usuário"] = // Coloque o nome ou Id do Usuário aqui como String.
meuCookie.Expires = DateTime.Now.AddMinutes(60);
Response.Cookies.Add(meuCookie);

Reading:

var meuCookie = new HttpCookie("MeuCookie");
meuCookie = Request.Cookies["MeuCookie"];

if (meuCookie == null) 
    throw new Exception("Informação do usuário não encontrada.");

var usuario = meuCookie.Values["Usuário"];
    
02.02.2017 / 18:39