Let's say you have a popular app and users want to register, but nobody wants to spend time filling out another signup form, coming up with another unique password, and remembering it. In those cases, third-party authentication services are a real lifesaver.
Examples of popular third-party services:
- Google: every other user has a Google account.
- Facebook: despite its ups and downs, it remains a popular authorization tool.
- GitHub: often used by developers.
- LinkedIn: ideal for business communities.
Third-party services let users sign in to your app using an existing account. This improves convenience (no new passwords!) and gives you access to verified info like an email address.
How OAuth2 helps integrate third-party services
OAuth2 provides a convenient mechanism for using third-party services so that your application (the "client") can request access to a user's resources from the authorization server of a third-party provider. The key point is that everything works via access tokens, not by passing passwords, which makes the process secure.
The basic idea is:
- Your app redirects the user to the authorization server (for example, Google).
- The user grants permission to access.
- The authorization server issues an access token to your app.
- Using that token, your app can securely interact with the third-party provider's resource server.
Authorization Flow
Authorization Flow is one of the OAuth2 flows used to give third parties (i.e., your app) access to a user's resources with the user's consent.
Let's break down the key steps:
1. Authorization request Your app redirects the user to the authorization URL. A typical URL looks like this:
https://accounts.google.com/o/oauth2/auth?
response_type=code&
client_id=YOUR_CLIENT_ID&
redirect_uri=YOUR_REDIRECT_URI&
scope=email profile&
state=xyz
Here:
- responsetype=code — indicates that we want to use the Authorization Code Flow.
- clientid — the identifier of your application (obtained when registering with the third-party provider).
- redirect_uri — the URL where the service will send the user back after authorization.
- scope — specifies which data the user should grant access to.
- state — used to prevent cross-site request forgery (CSRF).
2. The user grants permission After the redirect, the user sees the authorization screen provided by the provider (for example, Google). Here the user can decide whether to give your app access.
3. Receiving the Authorization Code If the user agrees, the authorization server redirects them back to your redirect_uri, adding a code parameter to the URL:
https://yourapp.com/callback?code=4/SOME_AUTHORIZATION_CODE&state=xyz
Your app should verify the state value to make sure the request came from a trusted source.
4. Exchanging the Authorization Code for an Access Token Now your app sends a POST request to the authorization server to exchange the code for a token:
POST https://oauth2.googleapis.com/token
Content-Type: application/x-www-form-urlencoded
code=4/SOME_AUTHORIZATION_CODE&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET&
redirect_uri=YOUR_REDIRECT_URI&
grant_type=authorization_code
If everything goes well, you'll get a JSON response with the token:
{
"access_token": "ya29.a0ARrdaM...",
"expires_in": 3599,
"scope": "email profile",
"token_type": "Bearer",
"refresh_token": "1//09n6..."
}
5. Accessing resources With the access_token you obtained, your app can make requests to the third-party provider's resource server. For example, to get the user's profile:
GET https://www.googleapis.com/oauth2/v1/userinfo?alt=json
Authorization: Bearer ya29.a0ARrdaM...
How this looks in Spring Boot
Now for the fun part: implementing this flow in Spring Boot.
Step 1: Add dependencies to pom.xml To integrate Google OAuth2 you'll need the Spring Security OAuth2 dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
Step 2: Configure application.yml Put the keys you got from Google (or another provider):
security:
oauth2:
client:
registration:
google:
client-id: YOUR_CLIENT_ID
client-secret: YOUR_CLIENT_SECRET
scope: profile, email
redirect-uri: "{baseUrl}/login/oauth2/code/google"
authorization-grant-type: authorization_code
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v1/userinfo
Step 3: Set up the controller Create a controller to handle successful authentication:
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/user")
public String user(@AuthenticationPrincipal OAuth2User principal) {
return "Hello, " + principal.getAttribute("name");
}
}
Step 4: Run the app Start your app and go to /oauth2/authorization/google. You'll be redirected to Google to authorize. After successful authorization you'll land on /user, where you'll see a greeting with your name.
Common errors and fixes
- Redirect error: if
redirect_uriis configured incorrectly, Google will return an error. Make sure it exactly matches what you've set up in the Google Console. - Insufficient permissions: if you forgot to request the necessary
scope, you won't receive the data you need. - Expired token: use refresh tokens to update the
access_token.
OAuth2 with third-party support is a powerful tool for convenient and secure sign-in to your apps. The implementation can be a bit tricky, but Spring Boot gives you handy tools that make the process easier. As one smart programmer said: "Why not let Google handle authentication?".
GO TO FULL VERSION