.Net Core 2.1 Web API同时使用JWT和JWT Cookie

Dou*_*oid 0 c# asp.net-core asp.net-core-webapi

我想将 JWT 存储在 cookie 中,并使用它来验证用户或 HTTP 标头中的不记名令牌。

目前我只使用 HTTP-Auth 标头并且它正在工作。

我尝试像这样使用 Identity Cookies 和 JwT:

[Authorize] //Cookie auth?!
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class ValuesController : ControllerBase
Run Code Online (Sandbox Code Playgroud)

启动.cs:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(...)

...

services.AddIdentity<ApplicationUser, IdentityRole>()
Run Code Online (Sandbox Code Playgroud)

我还尝试在AddAuthentication(). 它不起作用。

我的问题是如何为操作/控制器同时激活 JWT 和 ASP.NET 身份验证。

Kah*_*azi 5

根据您的描述,我猜测您的操作需要不止一次身份验证。

您可以添加使用AddJwtBearer和执行的多个身份验证架构AddIdentity,然后AuthorizeAttribute选择多个架构。

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme + ", " + Microsoft.AspNetCore.Identity.IdentityConstants.ApplicationScheme)]
Run Code Online (Sandbox Code Playgroud)

  • 将其更改为“Bearer,Identity.Application”,它似乎有效:)我只需要一种简化它的方法,所以我不必将“[Authorize(AuthenticationSchemes =“Bearer,Identity.Application”)” ]` 在每个操作/控制器之上。有任何想法吗? (3认同)