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

前端之家收集整理的这篇文章主要介绍了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认证,并且不知道令牌认证机制,因为它不是一个非常适合网页认证开始。

猜你在找的asp.Net相关文章