Web API 2 OWIN不记名令牌的用途是什么?

我想了解MVC 5中的单页面应用程序模板中的新OWIN承载令牌authentication过程。如果我错了,请更正我的OAuth密码客户端authenticationstream程,承载令牌authentication通过检查httpauthentication请求标头对于承载访问令牌代码来查看请求是否经过authentication,它不依赖于cookie来检查特定的请求是否被authentication。

根据这个职位:

使用Web API示例的OWIN承载令牌authentication

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

GrantReourceOwnerCredentials函数不仅仅是用这一行来编写票证:context.Validated(ticket); 但它也组成一个cookie的身份,并将其设置为cookie与此行:context.Request.Context.Authentication.SignIn(cookiesIdentity);

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

在SPA模板中实际上有两个单独的authentication机制启用 – cookieauthentication和令牌authentication。 这使得MVC和Web API控制器操作都可以进行身份​​validation,但需要一些额外的设置。

如果你看一下WebApiConfig.Register方法,你会看到这行代码:

  config.SuppressDefaultHostAuthentication(); 

这会告诉Web API忽略cookie身份validation,这可以避免您在问题中发布的链接中解释的许多问题 :

“… SPA模板使得应用程序cookie中间件也成为活动模式,以便启用其他场景(如MVC身份validation),因此,如果请求具有会话cookie但没有持有者令牌,Web API仍将被validation。另一个负面影响是,如果请求是未经授权的,那么这两个中间件组件都会对它提出质疑,cookie中间件会将401响应改为302,redirect到login页面。这也不是你想要的Web API请求。“

所以,现在调用config.SuppressDefaultHostAuthentication()需要授权的Web API调用将忽略随请求一起自动发送的cookie,并查找以“Bearer”开头的Authorization标头。 MVC控制器将继续使用cookie身份validation,并且对令牌身份validation机制一无所知,因为它不适合开始进行网页身份validation。

cookie的存在也让我感到困惑,因为在一个不记名的令牌authentication场景中显然是没有必要的……在这篇文章中,作者剖析了个人账户模板,并且有关于cookie的说法如下:

该方法还设置了一个应用程序cookie。 我没有看到一个很好的理由。

我的猜测是,模板的作者想要展示不同types的authentication逻辑的例子,在这种特殊情况下,他们想要展示如何将authentication信息存储在承载令牌authenticationJSON有效载荷以及标准authenticationcookie。

JSONauthentication有效载荷被设置为还包括附加的(不必要的)未encryption属性(用户ID),除了encryption票据之外,似乎也支持这一理论:

 var properties = CreateProperties(user.UserName); var ticket = new AuthenticationTicket(oAuthIdentity, properties); 

看起来模板的作者想要提供一些有用的例子,而不是实现不记名令牌authentication所需的最低限度的例子。 这也在上面的链接文章中提到。

cookie有一个重要的目的。 它的值包含可以通过客户端JavaScript在您的页面上提取的不记名令牌。 这意味着如果用户点击F5或刷新页面,cookie通常会持续存在。 当页面重新加载时,您的客户端JavaScript可以从cookie中获取不记名令牌。