Web API 2 OWIN Bearer令牌的目的是什么?

gav*_*vin 36 owin katana asp.net-mvc-5 asp.net-web-api2

我试图了解MVC 5中单页应用程序模板中新的OWIN Bearer Token身份验证过程.如果我错了请更正我,对于OAuth密码客户端身份验证流程,承载令牌身份验证通过检查http授权请求标头来工作对于承载访问令牌代码,以查看请求是否经过身份验证,它不依赖cookie来检查特定请求是否经过身份验证.

根据这篇文章:

使用Web API示例进行OWIN承载令牌认证

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    using (IdentityManager identityManager = _identityManagerFactory.CreateStoreManager())
    {
        if (!await identityManager.Passwords.CheckPasswordAsync(context.UserName, context.Password))
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        string userId = await identityManager.Logins.GetUserIdForLocalLoginAsync(context.UserName);
        IEnumerable<Claim> claims = await GetClaimsAsync(identityManager, userId);
        ClaimsIdentity oAuthIdentity = CreateIdentity(identityManager, claims,
            context.Options.AuthenticationType);
        ClaimsIdentity cookiesIdentity = CreateIdentity(identityManager, claims,
            _cookieOptions.AuthenticationType);
        AuthenticationProperties properties = await CreatePropertiesAsync(identityManager, userId);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }
}
Run Code Online (Sandbox Code Playgroud)

GrantReourceOwnerCredentials函数不仅使用以下行构成票证:context.Validated(ticket); 但它也组成了一个cookie标识,并使用以下行将其设置为cookie:context.Request.Context.Authentication.SignIn(cookiesIdentity);

所以我的问题是,这个函数中cookie的确切目的是什么?AuthenticationTicket不应该足够用于身份验证吗?

joe*_*dev 37

在SPA模板中,实际上启用了两个单独的身份验证机制 - cookie身份验证和令牌身份验证.这样可以对MVC和Web API控制器操作进行身份验证,但需要一些额外的设置.

如果您查看WebApiConfig.Register方法,您将看到以下代码行:

    config.SuppressDefaultHostAuthentication();
Run Code Online (Sandbox Code Playgroud)

这告诉Web API忽略cookie身份验证,这可以避免在您在问题中发布的链接中解释的一系列问题:

"... SPA模板也将应用程序cookie中间件作为活动模式启用,以便启用其他方案,如MVC身份验证.因此,如果请求具有会话cookie但没有持票人令牌,Web API仍将被验证.这可能不是你的希望您对API的CSRF攻击感到尊敬.另一个负面影响是,如果请求未经授权,两个中间件组件都会对其提出质疑.Cookie中间件会将401响应更改为302以重定向到登录页面.这也不是你想要的Web API请求."

因此,现在config.SuppressDefaultHostAuthentication()调用需要授权的Web API调用将忽略与请求一起自动发送的cookie,并查找以"Bearer"开头的Authorization标头.MVC控制器将继续使用cookie身份验证,并且不知道令牌身份验证机制,因为它不适合开始的网页身份验证.

  • 要添加到此,CookieAuthenticationOptions中有一个名为CookieHttpOnly的字段.如果将其设置为true,浏览器将根本不会使用JavaScript生成的API请求发送cookie,从而在调试时节省一些带宽和潜在的混淆. (2认同)