Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have multiple authentication cookies for a single app programmatically

I am writing a content management system where the user can create multiple sites inside the app. Each site can have authentication. I am trying to figure out how to have multiple authentication cookies for the app without having to add each one to the web.config. I need to create them programmatically when the application starts up. Is this possible?

Ex.

SecureApp: http://localhost/CTMS - Needs authentication to update sites

CustomSite: http://localhost/CTMS/Custom1 - Needs authentication separate from SecureApp

Hopefully this makes sense.

like image 838
Leslie Hanks Avatar asked Mar 21 '12 21:03

Leslie Hanks


People also ask

Can cookies be used for authorization?

Cookie authentication uses HTTP cookies to authenticate client requests and maintain session information. It works as follows: The client sends a login request to the server.

Where are authentication cookies stored?

Cookie-based Authentication The cookie is typically stored on both the client and server. The server will store the cookie in the database, to keep track of each user session, and the client will hold the session identifier. Cookie-based authentication works like this: User logins by entering credentials.


1 Answers

You can do this -

FormsAuthenticationTicket _ticket = new FormsAuthenticationTicket(_version, _name, _issueDate, _expirationDate, _isPersistent, _userData, _cookiePath);

string _encryptedTicket = FormsAuthentication.Encrypt(_ticket);

HttpCookie _cookie = new HttpCookie("customticket", _encryptedTicket);

HttpContext.Current.Response.Cookies.Add(_cookie);

Then you can write code to check incoming requests to see if they have this cookie -

HttpCookie _cookie = HttpContext.Current.Request.Cookies["customticket"];

if(_cookie){

_encryptedTicket = _cookie.Value;
FormsAuthenticationTicket _ticket = FormsAuthentication.Decrypt(_encryptedTicket);

    if(!_ticket.Expired) {
        IIdentity _identity = new FormsIdentity(_ticket);
        IPrincipal _principal = new GenericPrincipal(_identity, new string[0]); //Identity plus string of roles.
    }
}
else{
//dostuff
}
like image 167
Duncan Gravill Avatar answered Sep 30 '22 14:09

Duncan Gravill