Reputation: 17002
I am having difficulty figuring out how to set the current user in an ASP.NET MVC 5 application that uses ASP.NET Identity.
We use a Web Service that encapsulates authentication. A function calls that service and gets back a JWT token that can be "unwrapped" to retrieve the ClaimsIdentity
. It's my understanding that all you should need to do, at that point, is call HttpContext.GetOwinContext().Authentication.SignIn()
and pass the ClaimsIdentity
to establish the current user and get that user to persist across requests.
However, this doesn't seem to be the case. If I query this.User
in the controller or the view afterwards, it's an anonymous user (this.User.Identity.IsAuthenticated
evaluates to false
). Also, refreshing the page or redirecting makes it obvious that there's no current user (again, this.User.Identity.IsAuthenticated
evaluates to false
).
When I inspect the identity I've retrieved from AccountHelper
, all the data is there. It's fully populated with a name, an ID, and a full suite of claims.
So what is the right way to establish the current user and get it to persist across requests?
// This call authenticates a user with the provided credentials against our user store
// and returns a bearer token and a ClaimsIdentity.
var response = new AccountHelper().AuthenticateUser(credentials);
if (response.IsAuthenticated) // This is true
{
// This comes back with a fully populated identity, as expected.
var claimsIdentity = response.ClaimsIdentity;
// This call has no effect, whatsoever. It doesn't set the current user.
HttpContext.GetOwinContext()
.Authentication
.SignIn(new AuthenticationProperties { IsPersistent = true }, claimsIdentity);
Upvotes: 0
Views: 220
Reputation: 21476
First of all, did you miss .Current
in your code sample?
It should be
HttpContext.Current.GetOwinContext()
.Authentication
.SignIn(...);
Secondly, I'm assuming you've setup cookie authentication in your app?
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
...
});
Here setting the authentication type is important! And when you generate the claims identity and before you pass it into the .SignIn()
method, the claims identity needs to have the same authentication type so that they can talk!
I would use .CreateIdentityAsync()
method from the UserManager
class to create the identity instead, because you can pass the authentication type in as one of the parameters:
// Create an application user from your claim identity?
var appUser = new AppUser { ... };
// And pass the user into manager to create the identity with the same authentication
// type you used when you setup the cookie authentication
var claimsIdentity = _userManager.CreateIdentityAsync(appUser,
CookieAuthenticationDefaults.AuthenticationType);
I am using this way to impersonate users for admins that have developer role so that we can test the app.
Upvotes: 1