使用Expo构建连接Epic的应用时遭遇PKCE错误求助
问题代码
import { useAuthRequest, CodeChallengeMethod, makeRedirectUri, } from "expo-auth-session" const { codeChallenge, codeVerifier } = pkceChallenge(); const [ , , promptAsync] = useAuthRequest( { usePKCE: true, responseType: "code", clientId: epicClientId, redirectUri, scopes: ['fhirUser'], codeChallengeMethod: CodeChallengeMethod.S256, codeChallenge: codeChallenge, extraParams: { aud: 'my FHIR R4 URL' } }, { authorizationEndpoint: 'authorizationEndpoint from epic', tokenEndpoint: "tokenEndpoint from epic", } );
错误信息
{"authentication": null, "error": [Error: The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. More info: PKCE required for unsecured redirects], "errorCode": null, "params": {"error": "invalid_request", "error_description": "PKCE required for unsecured redirects", "state": "6Tul1Tw6mW"}, "type": "error", "url": "exp://192.168.1.9:8081/?error=invalid_request&error_description=PKCE+required+for+unsecured+redirects&state=6Tul1Tw6mW"}
排查方向
确认
redirectUri的一致性
用makeRedirectUri生成符合Expo本地环境的地址,确保和Epic后台配置的重定向URI完全匹配,包括exp://协议、IP、端口,甚至自定义路径(如果有配置)。本地Expo重启后IP可能变化,每次启动要核对当前地址是否在Epic的允许列表内。const redirectUri = makeRedirectUri({ scheme: 'your-app-scheme', // 若配置了自定义scheme需填写 path: '/oauth-redirect', // 按需调整,需和Epic配置一致 });校验PKCE参数完整性
确保pkceChallenge是从expo-auth-session正确导入的,codeChallenge和codeVerifier是成对生成且未被篡改。Epic要求PKCE必须使用S256方法,确认codeChallengeMethod确实设置为CodeChallengeMethod.S256。检查请求参数传递
开启Expo网络日志,查看发送到Epic授权端点的实际请求参数,确认code_challenge、code_challenge_method、response_type=code这些PKCE核心参数是否存在且格式正确。同时核对extraParams中的aud参数是否符合Epic的格式要求。核对Epic应用配置
确认你的Epic应用被设置为公共客户端(Public Client),公共客户端强制要求使用PKCE。另外检查Epic是否允许exp://协议的重定向URI,部分服务可能对非HTTPS地址有特殊限制。排查
useAuthRequest参数遗漏
再次确认usePKCE参数是否明确设置为true,避免变量覆盖或拼写错误。同时检查是否手动设置了错误的state参数(expo-auth-session会自动生成,手动设置可能导致不匹配)。
内容的提问来源于stack exchange,提问作者wuguidashi

