skip to Main Content

I’m trying to authenticate the user via Google authentication services. I’m already using Laravel sanctum successfully in terms of allowing users to login and register in the app.

This time, I’d like to add additional way for user to authenticate by using Google Identity services. I’m simply trying to hit the dd("test"); to see if I’m even able to hit the endpoint but it turns out I can’t.

With the code below, I’m getting an error that says POST http://localhost:8000/api/google-login 401 (Unauthorized) even though I’m putting the access token in the header.

I’m able to successfully grab the user object via the JWT as I see it being logged in the console.

However, I’m unable to redirect to the gallery component and I remain on the Home page despite successfully grabbing the user object via JWT. Redirecting to the gallery component is what’s the current behavior when a user successfully logs in or registers via Laravel sanctum (this functionality already works as I’ve mentioned above).

I’m not sure what’s going on as I’ve hit a wall on this. Any feedback would be much appreciated!

Here’s api.php

Route::middleware('auth:sanctum')->post('/google-login', [AuthController::class, 'googleLogin']);

Here’s AuthController.php

public function googleLogin(Request $request)
{
    dd("test");

    $token = $request->input('token');

    // Validate and process the token, obtain user data from Google Identity Services

    // Assuming you have retrieved the user data from Google Identity Services
    $user = [
        'name' => 'John Doe',
        'email' => '[email protected]',
        // Other user data...
    ];

    // Create a new Sanctum token for the authenticated user
    $accessToken = $this->createToken($user);

    return response()->json([
        'access_token' => $accessToken,
        'user' => $user,
    ]);
}

Here’s Home.js

useEffect(() => {
    // Using window.onload to ensure that the code is executed
    // only after the Google Sign-In library is fully loaded
    // in the app.blade.php file
    /* global google */
    window.onload = function () {
        google.accounts.id.initialize({
            client_id: 'my-client-id.com',
            callback: handleCallbackResponse
        });

        google.accounts.id.renderButton(
            document.getElementById('signInDiv'),
            { theme: "outline", size: "large" }
        )
    };
}, []);


function handleCallbackResponse(response) {
    console.log("response", response);
    console.log("Encoded JWT ID token: " + response.credential);
    let userObject = jwtDecode(response.credential);
    console.log(userObject);

    // Make a POST request to your Laravel API endpoint for Google login
    ApiClient.post('/google-login', { token: response.credential }, {
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
        }
    })
        .then(response => {
            const { access_token, user } = response.data;

            // Store the access token and user object in local storage or cookies
            localStorage.setItem('access_token', access_token);
            localStorage.setItem('user', JSON.stringify(user));

            // Redirect to the Gallery component
            history.push('/gallery');
        })
        .catch(error => {
            console.log(error);
        });
}

function handleSignOut() {
    setUser(null);
    document.getElementById("signInDiv").hidden = false;
    localStorage.removeItem("user"); // Remove user object from local storage on sign out
}

2

Answers


  1. 401 (unauthorized) is due to permission issues as its indicated.
    usually this happens when a token is missed or also expired, here, it should be a problem with the CSRF token.

    Login or Signup to reply.
  2. You are trying to access the /api/google-login route unauthenticated, but it is using the auth:sanctum middleware.

    You need to either remove the middleware from the route, or use a token to authenticate the request (which is not safe in this case, because your token will be exposed in the frontend code).

    If you want to remove the middleware, you can do it like this:

    Route::post('/google-login', [AuthController::class, 'googleLogin']);
    

    If you want to use a token to authenticate the request, you can read about it in the Laravel Sanctum documentation.

    Also, you can use the web.php route, instead of the api.php.
    Laravel: AJAX request endpoints in routes/api.php or routes/web.php?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search