authentication - 为中间件处理的单个路由指定身份验证方案
问题描述
我有一个新的 ASP.Net Core 3 MVC 站点,已将 GraphQL 添加到HotChocolate中。我有用户使用基于 cookie 的身份验证和 Auth0 登录到 MVC 端:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("Auth0", options =>
{
...
});
但是对于 GraphQL 请求,我需要 JWT 身份验证,我会使用:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(config =>
{
...
});
他们都独立工作正常。Cookie auth 允许控制器使用;JWT auth 允许使用 GQL。但我不知道如何获取控制器的 cookie 身份验证和/graphql
路由的 JWT。
一点上下文:HotChocolate 使用自定义中间件来处理进入/graphql
路由的请求。它不在控制器上,所以我不能只用Authorize
属性指定方案,因为没有控制器可以把它放在上面。
类似问题
- 在 ASP.NET Core 中结合 cookie 和令牌身份验证 - 此处的答案(“使用框架”)含糊不清且毫无帮助。
- 配置不同的授权/身份验证方案- 这是 .Net Core 1.1,而不是 3.1。API 发生了很大变化。试图调整它,但运行时错误说
DefaultSignInScheme
是必需的。
(还有一些其他的,主要专注于结合 REST 和 MVC,但它们都用于控制器,所以场景有点不同。)
解决方案
我有同样的问题,所以我想我发布我的解决方案以防其他人可能有同样的问题。
Hot Chocolate 使用默认身份验证方案,因此在启动时我将 JWT 声明为默认值:
services.AddAuthentication(options =>
{
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
在任何需要 Cookie 身份验证的地方,我只需添加:
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
推荐阅读
- module - terraform 0.12 迁移后出现意外类型错误
- php - 我们可以在 php 类的单个方法中使用两个 mysql 查询吗?
- c - 为什么 f_print 在 SD 卡上无法正常工作?
- excel - 如何参考另一个工作簿 vba 在可见单元格上输入 vlookup 公式
- java - 如何使用 sse android 发布通知
- javascript - A-Frame 静音所有声音,包括按钮单击时的声音组件
- django - 动态路径:确保 urlpatterns 是路径列表
- c++ - shellcode 在作为单独代码单独运行和与 C++ 代码一起运行时调用不同的系统调用
- opencv - 在树莓派上使用 cmake 构建 opencv 时出错
- r - 如何根据给定字符的一次或多次出现来拆分字符串?