gpt4 book ai didi

asp.net-mvc-5 - Web API 2 OWIN Bearer Token cookie的用途?

转载 作者:行者123 更新时间:2023-12-03 07:50:50 25 4
gpt4 key购买 nike

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

根据这篇文章:

OWIN Bearer Token Authentication with Web API Sample

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 不应该足以用于身份验证目的吗?

最佳答案

在 SPA 模板中,实际上启用了两种独立的身份验证机制——cookie 身份验证和 token 身份验证。这启用了 MVC 和 Web API Controller 操作的身份验证,但需要一些额外的设置。

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

    config.SuppressDefaultHostAuthentication();

这告诉 Web API 忽略 cookie 身份验证,从而避免了 the link you posted in your question 中解释的许多问题。 :

"...the SPA template enables application cookie middleware as active mode as well in order to enable other scenarios like MVC authentication. So Web API will still be authenticated if the request has session cookie but without a bearer token. That’s probably not what you want as you would be venerable to CSRF attacks for your APIs. Another negative impact is that if request is unauthorized, both middleware components will apply challenges to it. The cookie middleware will alter the 401 response to a 302 to redirect to the login page. That is also not what you want in a Web API request."



所以现在调用 config.SuppressDefaultHostAuthentication()需要授权的 Web API 调用将忽略随请求自动发送的 cookie,并查找以“Bearer”开头的 Authorization header 。 MVC Controller 将继续使用 cookie 身份验证,并且对 token 身份验证机制一无所知,因为它一开始就不太适合网页身份验证。

关于asp.net-mvc-5 - Web API 2 OWIN Bearer Token cookie的用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20926979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com