首页 > 解决方案 > 为中间件处理的单个路由指定身份验证方案

问题描述

我有一个新的 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属性指定方案,因为没有控制器可以把它放在上面。

类似问题

(还有一些其他的,主要专注于结合 REST 和 MVC,但它们都用于控制器,所以场景有点不同。)

标签: authenticationjwtopenid-connectasp.net-core-3.1hotchocolate

解决方案


我有同样的问题,所以我想我发布我的解决方案以防其他人可能有同样的问题。

Hot Chocolate 使用默认身份验证方案,因此在启动时我将 JWT 声明为默认值:

    services.AddAuthentication(options =>
    {
        options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    })

在任何需要 Cookie 身份验证的地方,我只需添加:

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

推荐阅读