SpringBoot3 — OAuth2 Login, Default Config — Part 1
OAuth 2.0, which stands for “Open Authorization”, is a standard designed to allow a website or application to access resources hosted by other web apps on behalf of a user. Implementing O-Auth2 in a SpringBoot application is quite complex as there are multiple moving parts that we need to configure correctly. In this tutorial, we will start with the most basic default configuration first, and we will cover the more advanced configurations later.
The default configuration is quite straight forward
- Go to https://start.spring.io/ and create a new application, and include the dependencies shown below.
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
2. Next, just refer to the the documentation of SpringBoot https://docs.spring.io/spring-security/reference/servlet/oauth2/login/core.html and use the default configuration class as starting point.
package az.ingress.oauth2.springoauth2.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@RequiredArgsConstructor
public class SecurityConfig {
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
).oauth2Login(Customizer.withDefaults());
return http.build();
}
private ClientRegistration googleClientRegistration() {
return ClientRegistration.withRegistrationId("google")
.clientId("<google-client-id>")
.clientSecret("<google-client-secret>")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("openid", "profile", "email", "address", "phone")
.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
.tokenUri("https://www.googleapis.com/oauth2/v4/token")
.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
.userNameAttributeName(IdTokenClaimNames.SUB)
.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.clientName("Google")
.build();
}
}
3. Create an app using Google API Console. Follow, Credentials -> Create Credentials -> Web Application.
Create a web application and configure the Authorized JavaScript origins, and Authorized redirect UTIs correctly.
4. In the above configuration, replace the google-client-id and google-client-secret with the Client ID and Client secret of your app.
.clientId("google-client-id")
.clientSecret("google-client-secret")
5. Create a simple controller like below to see if we are able to retrieve user info from the auth provider.
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
public class WelcomeController {
@GetMapping
public Object sayHello(Authentication authentication) {
return authentication.getPrincipal();
}
}
5. That is all, just navigate to http://localhost:8080/login which will display the default login page configuration,
Click on Google which should open Google accounts page,
Congratulations, you have the user details in your app.
Now, we made the simplest and easiest configuration, in Part2 we will implement the logic to save user info into our databae.