使用Axios+Google登录,Auth0 access_token无法获取用户信息求助
排查无法获取Auth0用户数据的原因
核心问题1:授权阶段未请求用户信息所需Scope
在startAuthFlow方法中,构建授权URL时仅传入offline_access scope,而openid profile email这些用于获取用户信息的权限并未在授权请求中声明。Auth0的权限体系要求必须在用户授权环节明确请求所需scope,否则生成的access_token将不具备访问用户数据的权限。
修正代码:
startAuthFlow(): string { const params = new URLSearchParams({ response_type: 'code', client_id: this.client_id, redirect_uri: this.redirect_uri, scope: 'openid profile email offline_access' // 合并所有需要的权限 }) const authURI = `https://${this.domain}/authorize?${params.toString()}` return authURI }
核心问题2:UserInfo接口请求冗余传递Scope参数
getUserInfo方法中,向/userinfo接口发起请求时额外添加了scope参数,这完全没必要。UserInfo接口的访问权限由access_token本身携带的scope决定,传递多余参数可能干扰请求逻辑,导致返回异常。
修正代码:
async getUserInfo(accessToken: string) { const userInfoEndpoint = `https://${this.domain}/userinfo` try { const response = await axios.get(userInfoEndpoint, { headers: { Authorization: `Bearer ${accessToken}` } }) return response.data } catch (error) { throw error } }
潜在问题:Token交换请求的Content-Type不规范
exchangeCodeForToken方法中,直接以JSON格式发送请求体,但Auth0的/oauth/token接口要求使用application/x-www-form-urlencoded格式。虽然当前能获取到access_token,但这是潜在的不稳定因素,建议修正为标准格式:
修正代码:
private async exchangeCodeForToken(code: string) { const tokenEndPoint = `https://${this.domain}/oauth/token` const payload = new URLSearchParams({ grant_type: 'authorization_code', client_id: this.client_id, client_secret: '[my client secret]', code, redirect_uri: this.redirect_uri, scope: 'openid profile email' }) try { const response = await axios.post(tokenEndPoint, payload) const { access_token, id_token, refresh_token } = response.data return { access_token, id_token, refresh_token } } catch (error) { throw error } }
内容的提问来源于stack exchange,提问作者Souvik De
相关产品推荐
相关产品推荐

