同时使用不记名令牌和 cookie 身份验证 [英] Using bearer tokens and cookie authentication together

查看:24
本文介绍了同时使用不记名令牌和 cookie 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单页应用程序 - 或多或少基于 MVC5 SPA 模板 - 使用承载令牌进行身份验证.

I have a single page app - more or less based on the MVC5 SPA template - using bearer tokens for authentication.

该站点还有几个需要保护的传统 MVC 页面,但使用了cookie 身份验证.

The site also has a couple of conventional MVC pages which need to be secured, but using cookie authentication.

在 Startup.Auth 中,我可以启用两种类型的授权:

In Startup.Auth I can enable both types of authorisation:

app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOAuthBearerTokens(OAuthOptions);

然而,这似乎有副作用,因为每当从 SPA 发送 AJAX 请求时,它都会发送标头中的承载令牌 cookie.

However, this seems to have a side-effect in that whenever an AJAX request is sent from the SPA, it sends both the bearer token in the header and the cookie.

而我真正想要的行为是承载令牌用于 WebAPI 调用,并且仅用于 MVC 调用的 cookie.

Whereas the behaviour I really want is that only the bearer token is used for WebAPI calls, and only the cookie for MVC calls.

我还希望 MVC 调用在未授权时重定向到登录页面(设置为 CookieAuthenticationOption),但显然我不希望在进行 API 调用时发生这种情况.

I'd also like the MVC calls to redirect to a login page when not authorised (set as a CookieAuthenticationOption), but obviously I don't want this to happen when making an API call.

有没有办法在一个应用程序中使用这种类型的混合模式身份验证?也许通过路径/路由过滤器?

Is there some way to have this type of mixed-mode authentication within one application? Perhaps through a path/route filter?

推荐答案

我想我已经解决了:-

Startup.Auth 正在连接 OWIN 管道,因此在那里包含 Cookie 和令牌是正确的.但是对 cookie 选项的一项更改指定了它应该应用于的身份验证类型:

Startup.Auth is wiring up the OWIN pipeline, so it is right to include Cookies and Tokens there. But one change to the cookie options specifies the authentication type it should apply to:

CookieOptions = new CookieAuthenticationOptions
{
  AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie   
};

然后我需要将 WebAPI 配置为仅使用令牌:

Then I needed to configure WebAPI to only use tokens:

public static void Configure(HttpConfiguration config)
{
   // Configure Web API to use only bearer token authentication.
   config.SuppressDefaultHostAuthentication();
   config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
}

这似乎达到了我想要的.WebAPI 仅使用不记名令牌而不使用 cookie,并且一些传统的 MVC 页面在登录后使用 cookie(使用 AuthenticationManager).

This seems to achieve what I want. WebAPI just uses bearer tokens and no cookies, and a few conventional MVC pages use cookies once logged in (using the AuthenticationManager).

这篇关于同时使用不记名令牌和 cookie 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆