asp.net-mvc-5 – Web API 2 OWIN承载令牌的目的cookie?

我试图理解在MVC 5中的单页应用程序模板中的新OWIN承载令牌认证过程。请纠正我,如果我错了,对于OAuth密码客户端认证流,承载令牌认证通过检查http授权请求头对于承载访问令牌代码来查看请求是否被认证,它不依赖于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,_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的确切目的是什么?认证标签不应该足够好用于认证目的吗?

解决方法

在SPA模板中,实际上有两个单独的验证机制启用 – cookie验证和令牌验证。这启用了对MVC和Web API控制器操作的认证,但需要一些额外的设置。

如果你看一下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”开头的授权标头。 MVC控制器将继续使用cookie认证,并且不知道令牌认证机制,因为它不是一个非常适合网页认证开始。

相关文章

引言 本文从Linux小白的视角, 在CentOS 7.x服务器上搭建一个...
引言: 多线程编程/异步编程非常复杂,有很多概念和工具需要...
一. 宏观概念 ASP.NET Core Middleware是在应用程序处理管道...
背景 在.Net和C#中运行异步代码相当简单,因为我们有时候需要...
HTTP基本认证 在HTTP中,HTTP基本认证(Basic Authenticatio...
1.Linq 执行多列排序 OrderBy的意义是按照指定顺序排序,连续...