I'm implementing simple login/password authentication using WebAPI/Owin 3.0. Here is my config method:
public void ConfigureAuth(IAppBuilder app) {
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions() {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/#sign-in")
});
}
Here is Login method
[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController {
[AllowAnonymous]
[Route("Login")]
public async Task<IHttpActionResult> Login(LoginBindingModel login) {
ApplicationUser user = await UserManager.FindAsync(login.Email, login.Password);
if(user != null) {
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
return Ok("OK");
}
return BadRequest("Invalid email or password");
}
}
I can see authentication cookie coming from the server after I send a request to the Login method. I also see that the cookie is sent back to the server when sending further requests. However, the server returns 401 Unauthorized response.
I put a breakpoint into the AuthorizeAttribute.IsAuthorized method. It turned out that actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false because AuthenticationType is null and there are no claims. Original identity in the Login method had 4 claims and its IsAuthenticated property was true.
Why does the Identity loses all its Claims and AuthenticationType values?
I'm testing using local IISExpress server with app running on localhost domain.
It turned out that Cookie authentication conflicts with SuppressDefaultHostAuthentication option. Disable this in WebApiConfig.cs to solve the problem.
config.SuppressDefaultHostAuthentication();
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