steps to get current logged in user ID C#

 

Step 1: After Login Get User details and store in a list.
List<LoginUsers> loginUsers = new  List<LoginUsers>

step 2: Serialize the list and create cookie

string userData = JsonConvert.SerializeObject(loginUsers);

ValidUser.SetAuthCookie(userData, userMaster.ID);

public static void SetAuthCookie(string userResponse, string userId)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
userId,
DateTime.Now,
DateTime.Now.AddMinutes(15),
false, //pass here true, if want to implement remember me functionality
userResponse); // the path for the cookie
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);
}

step 3: Open Global.asax and paste this

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null)
{
var serializeModel = JsonConvert.DeserializeObject<UserMaster>(authTicket.UserData);
var newUser = new CustomPrinciple(authTicket.Name)
{
//Mention Required Fields for eg
ID = serializeModel.ID
};
HttpContext.Current.User = newUser;
}
}
}
step 4:Create a class file with name customprinciple and mention required fields

That’s it Now Application is Authenticated and logged in user ID can be accessed using

var user = (CustomPrinciple)System.Web.HttpContext.Current.User;

string ID = user.ID

for Authentication

if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
//your code
}

That’s It Folks!!! Have a nice day

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s