【问题标题】:How To Store JWT Token In Cookie in ASP.NET Core 3 SPA App如何在 ASP.NET Core 3 SPA 应用程序的 Cookie 中存储 JWT 令牌
【发布时间】:2019-10-31 14:24:49
【问题描述】:

我有一个使用最新的“create-react-app”模板构建的默认 ASP.NET Core 3 应用程序。也就是说,在 startup.cs 中,我有以下代码来实例化我假设使用 OpenID 的 JWT 令牌生成器。我已经创建了 React 模板,但我认为在这种情况下这并不重要。,

        services.AddDefaultIdentity<ApplicationUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

登录后,我可以看到存储的 cookie 不是我的 JWT 令牌(这是我想要的)。 cookie 确实刮掉了 .AspNetCore.Identity.Application 属性,我认为它与 JWT 令牌有关,但我不知道如何。

我想将 JWT 令牌存储为 cookie 参数,以便在下一个请求时将其发送回服务器。如何将该 JWT 签名令牌作为 cookie 存储在我的 asp.net core 3 应用程序中?

【问题讨论】:

  • 假设客户端是浏览器,不可以直接放到sessionStorage吗?
  • 我需要在 cookie 中。

标签: asp.net-core asp.net-identity


【解决方案1】:

对于 JWT Authenticaiton,它通过标头 authorization: Bearer 检查请求。无需将令牌存储在 cookie 中。

如果您想获取自定义身份验证的令牌,您可以尝试从标头获取它。

要通过 jwt 身份验证,您需要使用授权标头而不是 cookie 传递令牌。

更新:

对于 React 和 Identity 库,身份验证是通过 AuthorizeService.js 进行的,您可以通过下面的 User 访问令牌:

async signIn(state) {
    await this.ensureUserManagerInitialized();
    try {
        const silentUser = await this.userManager.signinSilent(this.createArguments());
        this.updateState(silentUser);
        return this.success(state);
    } catch (silentError) {
        // User might not be authenticated, fallback to popup authentication
        console.log("Silent authentication error: ", silentError);

        try {
            if (this._popUpDisabled) {
                throw new Error('Popup disabled. Change \'AuthorizeService.js:AuthorizeService._popupDisabled\' to false to enable it.')
            }

            const popUpUser = await this.userManager.signinPopup(this.createArguments());
            this.updateState(popUpUser);
            return this.success(state);
        } catch (popUpError) {
            if (popUpError.message === "Popup window closed") {
                // The user explicitly cancelled the login action by closing an opened popup.
                return this.error("The user closed the window.");
            } else if (!this._popUpDisabled) {
                console.log("Popup authentication error: ", popUpError);
            }

            // PopUps might be blocked by the user, fallback to redirect
            try {
                await this.userManager.signinRedirect(this.createArguments(state));
                return this.redirect();
            } catch (redirectError) {
                console.log("Redirect authentication error: ", redirectError);
                return this.error(redirectError);
            }
        }
    }
}

【讨论】:

  • 我需要 cookie 的原因是我使用 JavaScript 发回并且 html 请求不是来自 asp.net 核心服务器。以前,登录后,它就是设置 auth cookie 的原因。我现在需要使用不记名令牌但找不到它。它不在 cookie 中。
  • @PeterKellner 你是如何申请令牌的?在服务器端,你可以试试var token = await HttpContext.GetTokenAsync("access_token");
  • @PeterKellner 检查客户端的更新以获取访问令牌。
  • 我把这段代码放在我的控制器中,当我登录时它返回令牌 null。public IEnumerable&lt;SessionRec&gt; GetSessionRecs() { var token = HttpContext.GetTokenAsync("access_token").Result;
猜你喜欢
  • 2018-10-22
  • 2015-09-15
  • 2016-09-13
  • 2021-02-20
  • 2020-08-09
  • 1970-01-01
  • 2021-10-13
  • 2021-01-21
  • 2017-12-13
相关资源
最近更新 更多