ASP.NET身份未正确授权

时间:2016-12-30 15:01:26

标签: c# asp.net asp.net-mvc asp.net-identity asp.net-authorization

我正在尝试创建一个简单的登录路由,此代码适用于登录并将cookie发送到浏览器:

[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();
}

以下是被称为SignInAsync的方法:

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);
}

这是我的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);
    }
}

尽管这会正确地将cookie发送到浏览器并且身份验证部分正常工作,但每当我调用另一个api控制器时,我一直认为该请求是未经授权的。我对身份框架不是很熟悉,所以我不知道发生了什么。

1 个答案:

答案 0 :(得分:2)

原始代码有2个错误

1。)默认身份验证类型不一致。他们应该都是ApplicationCookie

2.。)在Web API配置中,我必须注释掉以下几行:

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

这是将身份验证类型设置为“Bearer”,这与我的应用程序Cookie身份验证方法不一致,从而导致我遇到的问题。