Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI / Owin - Identity is not authorized after signing-in

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.

like image 347
Ivan Nikitin Avatar asked Dec 14 '22 18:12

Ivan Nikitin


1 Answers

It turned out that Cookie authentication conflicts with SuppressDefaultHostAuthentication option. Disable this in WebApiConfig.cs to solve the problem.

config.SuppressDefaultHostAuthentication();
like image 120
Ivan Nikitin Avatar answered Jan 05 '23 07:01

Ivan Nikitin