OAuth2 is an authorization framework that allows clients to access resources on behalf of a resource owner. This is commonly used for third-party applications to access user data from other websites and services. In this guide, we will show you how to implement a client in OAuth2 with Spring Boot.



Prerequisites

Before getting started, you should have a basic understanding of OAuth2 and Spring Boot. Additionally, you will need to have the following software installed:

  • Java 8 or later
  • Maven
  • An IDE (Eclipse or IntelliJ IDEA)
  • Postman (or a similar tool)


Creating the Spring Boot Project

The first step is to create a new Spring Boot project. You can do this by using the Spring Initializer website or by using the Spring CLI. For this guide, we will use the Spring Initializer website.

  1. Open your web browser and go to start.spring.io.
  2. Select the following options:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 2.5.0 or later
    • Group: com.example
    • Artifact: oauth2-client
    • Dependencies: Spring Web and Spring Security OAuth2 Client
  3. Click the “Generate” button to download the project files.
  4. Extract the files to a directory of your choice.


Configuring the Client

With the project created, the next step is to configure the client. In this example, we will be using the authorization code grant type. This means that the client will redirect the user to the authorization server to obtain an authorization code, which can then be used to obtain an access token.

Open the application.properties file and add the following properties:

spring.security.oauth2.client.provider.oidc.issuer-uri=http://localhost:8080/oauth/authorize
spring.security.oauth2.client.registration.oidc.client-id=client
spring.security.oauth2.client.registration.oidc.client-secret=secret
spring.security.oauth2.client.registration.oidc.redirect-uri=http://localhost:8081/callback

In this example, we are using an OpenID Connect (OIDC) provider, with the issuer URI set to http://localhost:8080/oauth/authorize, the client ID set to client, and the client secret set to secret. The redirect URI is set to http://localhost:8081/callback.

Next, open the OAuth2ClientApplication.java file and add the following code:

@EnableOAuth2Client
@RestController
public class OAuth2ClientApplication {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("/")
    public String index(Model model, OAuth2AuthenticationToken authentication) {
        OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient(
                authentication.getAuthorizedClientRegistrationId(), authentication.getName());
        model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
        model.addAttribute("userName", authentication.getName());
        return "index";
    }
}

This code sets up the OAuth2 client and creates a simple REST endpoint that displays the client name and user name.



Implementing the Callback

With the client configured, the next step is to implement the callback. This is where the client will receive the authorization code from the authorization server and exchange it for an access token.

Create a new file named CallbackController.java and add the following code:

@Controller
public class CallbackController {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("/callback")
    public String callback(Model model, OAuth2AuthenticationToken authentication) {
        OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient(
                authentication.getAuthorizedClientRegistrationId(), authentication.getName());
        model.addAttribute("accessToken", authorizedClient.getAccessToken().getTokenValue());
        return "callback";
    }
}

This code sets up the callback endpoint and retrieves the access token.



Running the Application

With the client and callback implemented, the final step is to run the application. You can do this by using the following command:

mvn spring-boot:run

Once the application is running, open Postman and send a GET request to http://localhost:8081/. You should be redirected to the authorization server to log in, and then redirected back to the client with the authorization code.



Conclusion

In this guide, we have shown you how to implement a client in OAuth2 with Spring Boot. By following these steps, you should be able to add OAuth2 authentication to your own applications. As always, be sure to thoroughly test your implementation before deploying it to production.



Leave a Reply