采用承载令牌和Cookie身份验证一起 [英] Using bearer tokens and cookie authentication together

查看:167
本文介绍了采用承载令牌和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);

不过,这似乎已经每当一个AJAX请求从SPA发出的副作用,它在头同时发送承载令牌饼干。

而行为我真正想要的是的承载令牌用于通话的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?

推荐答案

我觉得我的工作了这一点: -

I think I worked this out:-

Startup.Auth是布线了OWIN管道,所以它是正确的,包括饼干和令牌那里。但是,一个改变了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只是使用承载令牌和无饼干,以及一些传统的MVC页面使用登录后(使用的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天全站免登陆