asp.net-mvc 同时使用不记名令牌和 cookie 身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20953738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using bearer tokens and cookie authentication together
提问by Appetere
I have a single page app - more or less based on the MVC5 SPA template - using bearer tokensfor authentication.
我有一个单页应用程序 - 或多或少基于 MVC5 SPA 模板 - 使用不记名令牌进行身份验证。
The site also has a couple of conventional MVC pages which need to be secured, but using cookie authentication.
该站点还有几个需要保护的传统 MVC 页面,但使用cookie 身份验证。
In Startup.Auth I can enable both types of authorisation:
在 Startup.Auth 中,我可以启用两种类型的授权:
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOAuthBearerTokens(OAuthOptions);
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 andthe cookie.
但是,这似乎有副作用,因为每当从 SPA 发送 AJAX 请求时,它都会发送标头和cookie 中的承载令牌。
Whereas the behaviour I really want is that onlythe bearer token is used for WebAPI calls, and only the cookie for MVC calls.
而我真正想要的行为是只有不记名令牌用于 WebAPI 调用,只有 cookie 用于 MVC 调用。
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.
我还希望 MVC 调用在未授权时重定向到登录页面(设置为 CookieAuthenticationOption),但显然我不希望在进行 API 调用时发生这种情况。
Is there some way to have this type of mixed-mode authentication within one application? Perhaps through a path/route filter?
有没有办法在一个应用程序中进行这种类型的混合模式身份验证?也许通过路径/路由过滤器?
采纳答案by Appetere
I think I worked this out:-
我想我解决了这个问题:-
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:
Startup.Auth 正在连接 OWIN 管道,因此在那里包含 Cookie 和令牌是正确的。但是对 cookie 选项的一项更改指定了它应该应用于的身份验证类型:
CookieOptions = new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
};
Then I needed to configure WebAPI to only use tokens:
然后我需要将 WebAPI 配置为仅使用令牌:
public static void Configure(HttpConfiguration config)
{
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
}
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).
这似乎实现了我想要的。WebAPI 仅使用不记名令牌而不使用 cookie,并且一些传统的 MVC 页面在登录后使用 cookie(使用 AuthenticationManager)。
回答by xiongkailing
you can add jwt token to cookie (here my jwt token cookie name is "access_token") in http-only mode,and make a middleware like this
您可以在 http-only 模式下将 jwt 令牌添加到 cookie(这里我的 jwt 令牌 cookie 名称是“access_token”),并制作这样的中间件
public class JwtCookieMiddleware
{
private readonly RequestDelegate _next;
public JwtCookieMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext ctx)
{
if (ctx.Request.Cookies.TryGetValue("access_token", out var accessToken))
{
if (!string.IsNullOrEmpty(accessToken))
{
string bearerToken = String.Format("Bearer {0}", accessToken);
ctx.Request.Headers.Add("Authorization",bearerToken);
}
}
return this._next(ctx);
}
}
public static class JwtCookieMiddlewareExtensions
{
public static IApplicationBuilder UseJwtCookie(this IApplicationBuilder build)
{
return build.UseMiddleware<JwtCookieMiddleware>();
}
}
And you need use the middleware in startup like this:
您需要在启动时使用中间件,如下所示:
app.UseJwtCookie();
app.UseAuthentification();
app.UseMvc();
the above code will add jwt token to http request header if this request with a token cookie;
如果此请求带有令牌 cookie,则上述代码将 jwt 令牌添加到 http 请求标头;

