Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting user programmatically in ASP.NET MVC5

I want to log user programatically in ASP.NET MVC5. I'm setting auth cookies like this:

FormsAuthentication.SetAuthCookie(username, true);

I thouth it will be enough. But then I want to check value of Request.IsAuthenticated and it is always false. Also when I'm checking value of User.Identity.Name I'm getting empty string, not the username I passed earlier.

What should I do to make this work and set this values correctly?

EDIT: One more thing. I'm not using any login form, I'm passing user data (login and token) from different application.

like image 821
Paweł Reszka Avatar asked Dec 12 '22 04:12

Paweł Reszka


1 Answers

MVC5 comes with Identity instead of the older SimpleMembership and ASP.NET Membership. Identity doesn't use forms auth, hence why what you're doing has no effect.

To log a user in via Identity, first, you need an actual user instance, which you can get by doing something like:

var userManager = new UserManager<ApplicationUser>(context); 
var user = userManager.FindByName(username);

Then if you have a valid user (user != null), you need to generate a claims identity for that user via:

var identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

Finally, you can use that identity to sign the user in:

var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);

(If you want a persistent login, change that to true)

like image 75
Chris Pratt Avatar answered Dec 28 '22 11:12

Chris Pratt