0

I am trying to add social authentication to a laravel 5.8 API application using socialite. Following the documentation here https://laravel.com/docs/5.8/socialite#routing I created a SocialAuthController that wiill redirect the user to the provider auth page and handle the callback like this

...

use Socialite;

...

public function redirectToProvider($provider)
{
    return Socialite::driver($provider)->redirect();
}

public function handleProviderCallback($provider)
{
    // retrieve social user info
    $socialUser = Socialite::driver($provider)->stateless()->user();

    // check if social user provider record is stored
    $userSocialAccount = SocialAccount::where('provider_id', $socialUser->id)->where('provider_name', $provider)->first();

    if ($userSocialAccount) {

        // retrieve the user from users store
        $user = User::find($userSocialAccount->user_id);

        // assign access token to user
        $token = $user->createToken('string')->accessToken;

        // return access token & user data
        return response()->json([
            'token' => $token,
            'user'  => (new UserResource($user))
        ]);
    } else {

        // store the new user record
        $user = User::create([...]);

        // store user social provider info
        if ($user) {

            SocialAccount::create([...]);
        }

        // assign passport token to user
        $token = $user->createToken('string')->accessToken;
        $newUser = new UserResource($user);
        $responseMessage = 'Successfully Registered.';
        $responseStatus = 201;

        // return response
        return response()->json([
            'responseMessage' => $responseMessage,
            'responseStatus'  => $responseStatus,
            'token'           => $token,
            'user'            => $newUser
        ]);
    }
}

Added the routes to web.php

Route::get('/auth/{provider}', 'SocialAuthController@redirectToProvider');

Route::get('/auth/{provider}/callback', 'SocialAuthController@handleProviderCallback');

Then I set the GOOGLE_CALLBACK_URL=http://localhost:8000/api/v1/user in my env file.

When a user is successfully authenticated using email/password, they will be redirected to a dashboard that will consume the endpoint http://localhost:8000/api/v1/user. So in the google app, I set the URI that users will be redirected to after they are successfully authenticated to the same endpoint http://localhost:8000/api/v1/user

Now when a user tries to login with google, the app throws a 401 unauthenticated error.

// 20190803205528
// http://localhost:8000/api/v1/user?state=lCZ52RKuBQJX8EGhz1kiMWTUzB5yx4IZY2dYmHyJ&code=4/lgFLWpfJsUC51a9yQRh6mKjQhcM7eMoYbINluA58mYjs5NUm-yLLQARTDtfBn4fXgQx9MvOIlclrCeARG0NC7L8&scope=email+profile+openid+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email&authuser=0&session_state=359516252b9d6dadaae740d0d704580aa1940f1d..10ea&prompt=none

{
  "responseMessage": "Unauthenticated",
  "responseStatus": 401
}

If I change the URI where google authenticated users should be redirect to like this GOOGLE_CALLBACK_URL=http://localhost:8000/auth/google/callback the social user information is returned.

So how should I be doing it. I have been on this for a couple of days now.

Mena
  • 1,873
  • 6
  • 37
  • 77

1 Answers1

0

That is because you haven't put authorization in your header with your request. you don't need to redirect user if you are working with token, your app should be a spa project, so you will redirect him from your side using js frameworks. You need to send Authorization in your headers plus you need to specify it with your token which you returned it in your response like this:

    jQuery.ajaxSetup({
       headers: {
         'Authorization': 'Bearer '+token
       }
    });

or if you are using axios

   axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
Mohammed Aktaa
  • 1,345
  • 9
  • 14
  • Yes the issue is because is because the redirect route is using `auth`. But how can I set up the redirect route so that the token is returned to the app consuming the api, then they can use it in their own app? – Mena Aug 04 '19 at 15:55