Laravel对接GitLab OAuth2调用用户接口返回401 Unauthorized问题
Laravel 集成 GitLab OAuth2 调用用户接口返回401问题
问题表现
- 按官方文档实现GitLab OAuth2授权登录,回调阶段可正常获取
access_token - 携带获取到的token调用
https://gitlab.com/api/v4/projects接口可正常返回结果 - 同token调用
https://gitlab.com/api/v4/user获取用户信息时,接口返回{"message":"401 Unauthorized"}错误 - 相关配置项
client_id、client_secret、redirect_uri均已正确写入.env文件
现有实现代码
GitLab控制器回调方法
public function callback(Request $request) { $response = Http::withHeaders(['Accept' => 'application/json']) ->asForm() ->post('https://gitlab.com/oauth/token',[ 'client_id' => config('oauth.gitlab.client_id'), 'client_secret' => config('oauth.gitlab.client_secret'), 'code' => $request->get('code'), 'grant_type' => 'authorization_code', 'redirect_uri' => config('oauth.gitlab.callback_uri'), ]); $token = $response['access_token']; $response = Http::withHeaders(['Authorization' => 'token ' . $token]) ->get('https://gitlab.com/api/v4/user'); dd($response->body()); }
GitlabServices类授权链接生成方法
public static function link(): string { $params = [ 'response_type' => 'code', 'client_id' => config('oauth.gitlab.client_id'), 'redirect_uri' => config('oauth.gitlab.callback_uri'), 'scope' => 'read_user openid' ]; return 'https://gitlab.com/oauth/authorize?' . http_build_query($params); }
问题根因
- 认证头格式错误:GitLab OAuth2 接口要求使用标准Bearer Token认证格式,请求头中token前缀需要写
Bearer,现有代码写的是token,服务端无法识别携带的凭证,直接判定为未授权请求。 - 接口测试逻辑误判:
/api/v4/projects接口对公开项目支持匿名访问,之前用错误认证头请求时,服务端直接忽略了无效的认证信息,按匿名用户权限返回了公开项目数据,造成token携带方式正确的误判。授权链接配置的read_userscope本身权限足够,可正常调用用户信息接口。
修复方法
修改回调方法中调用用户接口的请求头,将token前缀从token改为Bearer即可,修复后的请求代码如下:
$response = Http::withHeaders(['Authorization' => 'Bearer ' . $token]) ->get('https://gitlab.com/api/v4/user');
修复后不要用公开的projects接口验证token有效性,直接调用user接口,能正常返回当前用户的id、用户名、邮箱等信息就说明认证流程完全正常。
内容的提问来源于stack exchange,提问作者Miron
相关产品推荐
相关产品推荐

