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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With