How to save username in MVC?

I am setting up my first MVC site, and I just implemented a security and presentation controller.

However, I do not understand how I can save registered user data through my controllers.

For example, a user logs in with an email / password. Then I can check if the letters and passwords match, and I do the following:

FormsAuthentication.SetAuthCookie(userLogin.UserName, false);
return View("../Home/Index");

Now let's say, for example, I want data to be displayed in the Index view, which only the user can see.

I have a table setup, but it is based on user_id.

Is it possible to save user_id at login or is there something already available to access their email (to the user)? (Then I could search for an identifier by email, if necessary)

My MVC is configured to use forms authentication:

<authentication mode="Forms">
  <forms loginUrl="~/Security/Login" timeout="2880" />
</authentication>

and I decorated the controllers with an [Authorize] annotation.

0
source share
2 answers
FormsAuthentication.SetAuthCookie(userLogin.UserName, false);

The above code just sets the authentication ticket inside the cookie.

Once the authenticated user sends the request, you still need to get the authorization ticket from the cookie and create the Principal object.

Global.asax.cs

void Application_AuthenticateRequest(object sender, EventArgs e)
{
   HttpCookie decryptedCookie = 
      Context.Request.Cookies[FormsAuthentication.FormsCookieName];

   FormsAuthenticationTicket ticket = 
      FormsAuthentication.Decrypt(decryptedCookie.Value);

   var identity = new GenericIdentity(ticket.Name);
   var principal = new GenericPrincipal(identity, null);

   HttpContext.Current.User = principal;
   Thread.CurrentPrincipal =HttpContext.Current.User;
}

Using

if (User.Identity.IsAuthenticated) {
   var username = User.Identity.Name;
}
+2
source

You can access the current user (username) in all controllers through

HttpContext.Request.RequestContext.HttpContext.User.Identity.Name

To find out any other information, you usually need to query the database based on the username

0
source

Source: https://habr.com/ru/post/1652703/


All Articles