laravel / socialite

Laravel wrapper around OAuth 1 & OAuth 2 libraries.
https://laravel.com/docs/socialite
MIT License
5.55k stars 939 forks source link

Gracefully handle provider errors #713

Closed Mat-Hartje closed 1 month ago

Mat-Hartje commented 1 month ago

Socialite Version

5.14.0

Laravel Version

11.10.0

PHP Version

8.2

Database Driver & Version

No response

Description

The oAuth provider can at times return errors (in my experience, this is most commonly due to the end user, declining to share their information with the requesting app)

Documentation: https://www.oauth.com/oauth2-servers/server-side-apps/possible-errors/

Errors are indicated by redirecting back to the provided redirect URL with additional parameters in the query string. There will always be an error parameter, and the redirect may also include error_description and error_uri.

When this happens, I would expect Socialite to gracefully handle this. For example, it could throw an explicit error similar to what it does for Invalid State.

Instead things end up failing with a Guzzle exception due to a 400 Bad Request

Client error: `POST https://oauth2.googleapis.com/token` resulted in a `400 Bad Request` response:
 {
   "error": "invalid_request",
   "error_description": "Missing required parameter: code"
 }

Steps To Reproduce

Mat-Hartje commented 1 month ago

Another lower effort option would be to update the docs to callout that this is something that needs to be handled

something like:

Route::get('/auth/callback', function () {
    if (request()->query('error')) {
      // handle errors: https://www.oauth.com/oauth2-servers/server-side-apps/possible-errors/
    }

    $user = Socialite::driver('github')->user();

    // $user->token
});
driesvints commented 1 month ago

Thanks @Mat-Hartje. I think adding this to the docs is a good idea so feel free to attempt a PR 👍