Home > Back-end >  GitLab oauth2 Laravel "{"message":"401 Unauthorized"}"
GitLab oauth2 Laravel "{"message":"401 Unauthorized"}"

Time:06-30

My gitLab controller. Links taken from the documentation. After submitting the form returns an error "{"message":"401 Unauthorized"}" . Token is coming, but i want to get username and email.

My gitLab controller

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

also link https://gitlab.com/api/v4/projects is work success

       dd($response->body());
      }


        

after checking I get an error 401. I don't understand why.

** My class 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);
}
  
   client_id, secret, redirect_uri store in .env

CodePudding user response:

If you getting 401 in response. Check if the token privileges to request data. Probably:

  1. Token is not attached with request.
  2. Token don't have privileges.

CodePudding user response:

adding helped me 'token_type'

 $token = $response->json('access_token');
   $tokenType = $response->json('token_type');

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

the connection was success and I received all the necessary information

  • Related