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

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);
}

问题根因

  1. 认证头格式错误:GitLab OAuth2 接口要求使用标准Bearer Token认证格式,请求头中token前缀需要写Bearer,现有代码写的是token,服务端无法识别携带的凭证,直接判定为未授权请求。
  2. 接口测试逻辑误判:/api/v4/projects接口对公开项目支持匿名访问,之前用错误认证头请求时,服务端直接忽略了无效的认证信息,按匿名用户权限返回了公开项目数据,造成token携带方式正确的误判。授权链接配置的read_user scope本身权限足够,可正常调用用户信息接口。

修复方法

修改回调方法中调用用户接口的请求头,将token前缀从token改为Bearer即可,修复后的请求代码如下:

$response = Http::withHeaders(['Authorization' => 'Bearer ' . $token])
    ->get('https://gitlab.com/api/v4/user');

修复后不要用公开的projects接口验证token有效性,直接调用user接口,能正常返回当前用户的id、用户名、邮箱等信息就说明认证流程完全正常。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 20:01:21