的WebAPI / Owin - 身份签约,后在未授权 [英] WebAPI / Owin - Identity is not authorized after signing-in

查看:605
本文介绍了的WebAPI / Owin - 身份签约,后在未授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实施使用的WebAPI / Owin 3.0简单的登录/密码认证。下面是我的配置方式:

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

下面的登录方法

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

}

我可以看到来自服务器后,我发送到登录方法的请求身份验证cookie。我也看到,发送进一步的请求时,cookie被发送回服务器。但是,服务器返回401未经授权响应。

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.

我把一个断点到AuthorizeAttribute.IsAuthorized方法。原来,
actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated == false,因为AuthenticationType为空,没有索赔。在登录方法原来的身份有4个索赔和其IsAuthenticated属性为true。

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.

为什么身份失去了所有的索赔和AuthenticationType价值?

Why does the Identity loses all its Claims and AuthenticationType values?

我使用的是本地主机上运行的域本地应用程序IISEx preSS服务器测试。

I'm testing using local IISExpress server with app running on localhost domain.

推荐答案

原来,这与燮pressDefaultHostAuthentication选项的Cookie认证冲突。在WebApiConfig.cs禁用此来解决这个问题。

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

config.SuppressDefaultHostAuthentication();

这篇关于的WebAPI / Owin - 身份签约,后在未授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆