Integrating LinkedIn Authentication in a Spring Boot 3 application
To integrate LinkedIn authentication in a Spring Boot application with Spring Security, you can use OAuth 2.0 authentication to authenticate users via LinkedIn. Spring Security 6+ provides OAuth 2.0 support for integrating third-party login services like LinkedIn. Here’s how to set up LinkedIn authentication with Spring Boot 3 and Spring Security 6+.
1. Add Dependencies
In your pom.xml, include the necessary dependencies for Spring Security and OAuth 2.0 support.
<dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<!-- Spring Boot Starter Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
<!-- Spring Boot Starter OAuth2 Login --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency>
<!-- Spring Boot Starter Test (optional) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency></dependencies>
2. Set Up LinkedIn Application
To enable LinkedIn authentication, you need to create a LinkedIn developer application. Follow these steps:
- Go to LinkedIn Developer Portal.
- Create a new application and get the Client ID and Client Secret.
- Configure the OAuth 2.0 Redirect URL in the LinkedIn application settings, e.g., http://localhost:8080/login/oauth2/code/linkedin.
3. Configure Application Properties
Add the OAuth 2.0 configuration in your application.properties or application.yml.
application.yaml
spring: security: oauth2: client: provider: linkedin: authorization-uri: https://www.linkedin.com/oauth/v2/authorization token-uri: https://www.linkedin.com/oauth/v2/accessToken user-info-uri: https://api.linkedin.com/v2/me user-name-attribute: id registration: linkedin: authorization-grant-type: authorization_code client-id: YOUR_LINKEDIN_CLIENT_ID client-name: LinkedIn client-secret: YOUR_LINKEDIN_CLIENT_SECRET redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}' scope: r_liteprofile,r_emailaddress
Replace YOUR_LINKEDIN_CLIENT_ID and YOUR_LINKEDIN_CLIENT_SECRET with the actual values from your LinkedIn application.
4. Configure Security for OAuth2 Login
In Spring Security 6+, you can configure OAuth 2.0 login with a SecurityFilterChain bean.
SecurityConfig.java
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationFilter;import org.springframework.security.oauth2.core.user.OAuth2User;import org.springframework.security.oauth2.core.OAuth2AuthenticationToken;import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
@Configurationpublic class SecurityConfig {
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf().disable() // Disable CSRF for simplicity (not recommended for production) .authorizeRequests() .antMatchers("/", "/home", "/login**", "/error").permitAll() // Allow public URLs .anyRequest().authenticated() // Require authentication for other URLs .and() .oauth2Login() // Enable OAuth2 login .defaultSuccessUrl("/home", true) // Redirect to /home after successful login .failureUrl("/login?error"); // Redirect to /login?error on failure
return http.build(); }
@Bean public OAuth2UserService<OAuth2AuthenticationToken, OAuth2User> oAuth2UserService() { return new DefaultOAuth2UserService(); // Default user service for extracting user details }}
5. Handle Authentication in Your Application
Once a user has authenticated via LinkedIn, the information will be available through the OAuth2User object. You can customize how user details are handled and store them in a database if needed.
For example, you can extract and display the user's LinkedIn profile information in a controller:
HomeController.java
import org.springframework.security.oauth2.core.user.OAuth2User;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.security.core.annotation.AuthenticationPrincipal;
@RestControllerpublic class HomeController {
@GetMapping("/home") public String home(@AuthenticationPrincipal OAuth2User oauth2User) { // Extracting user info from OAuth2User (LinkedIn profile info) String name = oauth2User.getAttribute("localizedFirstName") + " " + oauth2User.getAttribute("localizedLastName"); return "Welcome, " + name; }}
In this example, when the user logs in via LinkedIn, their first and last name are extracted from the OAuth2User object and displayed.
6. Running the Application
- Run your Spring Boot application.
- Visit the application in your browser (e.g., http://localhost:8080).
- Click the login button (the login page will redirect to LinkedIn for authentication).
- After authentication, you should be redirected to /home with the user’s LinkedIn profile information.
7. Optional: Customizing the Login Flow
You can customize the login flow by adding an OAuth2LoginSuccessHandler or an OAuth2LoginFailureHandler to handle success or failure scenarios based on your application requirements.
Final Notes:
- Security Considerations: Make sure to handle OAuth tokens and user data securely. In production, store sensitive data like Client ID and Client Secret in secure places (e.g., environment variables or a secret management service).
- LinkedIn API Limits: LinkedIn has API rate limits, so consider these when designing your app, especially if it involves making frequent API calls.