You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Cognito集成Okta OIDC遇PKCE必填错误及NextJS问题排查

问题描述

我在Okta中创建了采用Authorization Code授权类型的OIDC单页应用(SPA),随后在AWS Cognito中添加该Okta应用作为联邦身份提供商,Issuer URL为https://something.okta.com/oauth2/default,属性映射配置为email->email、family_name->family_name、given_name->given_name、username->sub。

在AWS Cognito用户池中,我创建了一个SPA应用客户端,使用Hosted UI登录页面。但点击登录页面中的Continue with Okta按钮时,出现错误:

Error: PKCE code challenge is required by the application.

我排查后发现URL中缺少code_challenge,于是在NextJS应用中实现了PKCE参数,但仍出现相同错误。我的登录按钮组件代码如下:

<button
      type="button"
      className="cursor-pointer w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 rounded-lg mb-2"
      onClick={async () => {
        // PKCE code verifier and challenge generation
        function base64UrlEncode(str: ArrayBuffer) {
          return btoa(String.fromCharCode(...new Uint8Array(str)))
            .replace(/\+/g, '-')
            .replace(/\//g, '_')
            .replace(/=+$/, '');
        }
        function generateRandomString(length: number) {
          const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
          let result = '';
          const values = window.crypto.getRandomValues(new Uint32Array(length));
          for (let i = 0; i < length; i++) {
            result += charset[values[i] % charset.length];
          }
          return result;
        }
        async function pkceChallengeFromVerifier(verifier: string) {
          const encoder = new TextEncoder();
          const data = encoder.encode(verifier);
          const digest = await window.crypto.subtle.digest('SHA-256', data);
          return base64UrlEncode(digest);
        }
        const codeVerifier = generateRandomString(128);
        const codeChallenge = await pkceChallengeFromVerifier(codeVerifier);
        sessionStorage.setItem('pkce_code_verifier', codeVerifier);
        // Replace these with your actual values
        const domain = 'domain.auth.ap-southeast-2.amazoncognito.com';
        const clientId = 'xxxxxxxxxxxx';
        const redirectUri = encodeURIComponent('http://localhost:3000');
        const authorizeUrl = `https://${domain}/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&code_challenge=${codeChallenge}&code_challenge_method=S256&identity_provider=Okta`;
        window.location.href = authorizeUrl;
      }}
    >
      Login with Okta
    </button>

待解决问题

  • Okta与AWS Cognito间哪项配置错误导致Hosted UI出现该错误?
  • 我的NextJS应用代码存在什么问题?

内容的提问来源于stack exchange,提问作者Hugh Bui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:57:13