/spring-react-google-oauth2

Google Oauth2 login scenario with Spring boot + React

Primary LanguageJava

spring-react-google-oauth2

Implementing Google OAuth2 login using Spring Boot and React.

The following diagram illustrates the OAuth implicit flow:

oauthFlow

Result

Demonstration of the Google OAuth login process:

google-oauth-login

How to start

Prerequiste

Before you begin, ensure you have created a Google OAuth credential.

Refer to this guide for assistance: Google OAuth Credentials

Important Note

While configuring 'Authorized JavaScript origins' in the Google Developer Console's Credential settings, remember to add both http://localhost and http://localhost:3000.

스크린샷 2023-12-07 오후 2 25 27

Spring boot

  1. In application.yml, replace app: googleClientId with your Google client ID and app: jwtSecret with a secret string (minimum 256 bits for enhanced security).
app:
  jwtSecret: "String longer than 256 bits"
  googleClientId: "your google client id"
  1. Execute the following commands in the terminal:
cd spring-oauth

./gradlew build

cd build/libs

java -jar oauth-0.0.1-SNAPSHOT.jar

Process Overview

  1. Validate the ID token received from the client.
  2. Create an account using the ID token information.
  3. Store the account in the database using Spring Data JPA and H2.
  4. Generate a custom JWT.
  5. Send a cookie containing the custom JWT back to the client.
  6. Include the JWT in the request header for API requests.
  7. JWT filter validates the JWT in each client request header.

REACT

  1. Update REACT_APP_GOOGLE_CLIENT_ID in react-oauth/.env with your Google client ID.
REACT_APP_API_URL="http://localhost:8080"
REACT_APP_GOOGLE_CLIENT_ID="your google client-id"
  1. Run the following commands:
cd react-oauth

npm install

npm start

Note: If you encounter a version conflict during npm install, try npm install --force.

Process Overview

  1. Log in with an existing Google account.
  2. Obtain an ID token from Google.
  3. Send the ID token to the server for authentication.
  4. Receive a cookie containing a JWT generated by the server.
  5. Request user information from the server using the cookie.
  6. Display the user information.