Spring Security OAuth 2 client support lets an application obtain access tokens and call a resource server for a user. With the authorization code flow, the application redirects unauthenticated users for consent, receives an authorization code, and exchanges it for a token. section 8.4
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency>
Add the Spring Boot starter to bring OAuth 2 client capabilities and Spring Security into the application. section 8.4
@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(
authorizeRequests -> authorizeRequests.anyRequest().authenticated()
)
.oauth2Login(
oauth2Login ->
oauth2Login.loginPage("/oauth2/authorization/taco-admin-client"))
.oauth2Client(withDefaults());
return http.build();
}
Require authentication for every request, enable OAuth 2 login, and activate client support with a SecurityFilterChain bean. section 8.4
spring:
security:
oauth2:
client:
registration:
taco-admin-client:
provider: tacocloud
client-id: taco-admin-client
client-secret: secret
authorization-grant-type: authorization_code
redirect-uri:
"http://127.0.0.1:9090/login/oauth2/code/{registrationId}"
scope: writeIngredients,deleteIngredients,openid
Register the client with its provider, credentials, authorization-code grant, redirect URI, and requested scopes. section 8.4
After login, a request-scoped service can retrieve the authorized client’s access token and attach it as a Bearer token to RestTemplate requests. section 8.4
