ASP.NET Identity not authorizing properly

150 views Asked by At

I am attempting to create a simple Login route and this code works fine for logging in and sending the cookie to the browser:

[Route("Login")]
[AllowAnonymous]
public async Task<IHttpActionResult> Login(UserBindingModel model)
{
    if (ModelState.IsValid)
    {              
        var user = await UserManager.FindUserAsync(model.username, model.password);

        if (user != null)
        {
            await SignInAsync(user, true);
            return Ok();
        }              
    }

    return BadRequest();
}

Here is the SignInAsync method that's being called:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    Authentication.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

Here is my IdentityConfig:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new TestUserStore());

        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = false,
        };
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }

        return manager;
    }

    public async Task<ApplicationUser> FindUserAsync(string username, string password)
    {
        var userStore = new TestUserStore();
        ApplicationUser user = await userStore.FindByNameAsync(username, password);
        return await Task.FromResult(user);
    }
}

Despite this sending the cookie to the browser correctly and the authentication portion working, whenever I call another api controller I keep getting that the request is unauthorized. I am not extremely familiar with the identity framework so I have no idea what's going on.

1

There are 1 answers

0
Alex Palacios On BEST ANSWER

There were 2 errors with my original code

1.) The Default Authentication Types were not consistent. They should have all been ApplicationCookie

2.) In the Web API config, I had to comment out the following lines:

  config.SuppressDefaultHostAuthentication();
  config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

This was setting the authentication type to "Bearer", which was inconsistent with my Application Cookie Authentication approach and thus causing the problems I encountered.