Implementing Google OAuth2 login using Spring Boot and React.
The following diagram illustrates the OAuth implicit flow:
Demonstration of the Google OAuth login process:
Before you begin, ensure you have created a Google OAuth credential.
Refer to this guide for assistance: Google OAuth Credentials
While configuring 'Authorized JavaScript origins' in the Google Developer Console's Credential settings, remember to add both http://localhost and http://localhost:3000.
- 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"
- Execute the following commands in the terminal:
cd spring-oauth
./gradlew build
cd build/libs
java -jar oauth-0.0.1-SNAPSHOT.jar
- Validate the ID token received from the client.
- Create an account using the ID token information.
- Store the account in the database using Spring Data JPA and H2.
- Generate a custom JWT.
- Send a cookie containing the custom JWT back to the client.
- Include the JWT in the request header for API requests.
- JWT filter validates the JWT in each client request header.
- 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"
- 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.
- Log in with an existing Google account.
- Obtain an ID token from Google.
- Send the ID token to the server for authentication.
- Receive a cookie containing a JWT generated by the server.
- Request user information from the server using the cookie.
- Display the user information.