Paweł Reszka
Paweł Reszka

Reputation: 1557

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.

Upvotes: 5

Views: 3233

Answers (2)

meda
meda

Reputation: 45490

Make sure form Athentication is enabled in your web.config file.

<system.web>
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
...
</system.web>

Upvotes: 2

Chris Pratt
Chris Pratt

Reputation: 239260

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)

Upvotes: 12

Related Questions