根据这篇文章:
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);
解决方法
如果你看一下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认证,并且不知道令牌认证机制,因为它不是一个非常适合网页认证开始。