liveBook · Manning

Spring Security OAuth 2 client

As explained in Spring in Action, Sixth Edition

The Spring Security module that implements OAuth2 client-side authorization flows, token acquisition, and authenticated resource requests.

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

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains dependency, filter-chain, registration, provider, token retrieval, and Bearer-header configuration without detailing protocol internals.
Examples
Uses a Taco admin client, YAML registration, a SecurityFilterChain, and a RestTemplate ingredient service.
What it assumes
Assumes a Spring Boot application and an OAuth 2 authorization server, while configuring client concepts explicitly.
What you can do after
Build it from scratch by configuring OAuth 2 login and forwarding retrieved access tokens to REST endpoints.
How it connects
Connects OAuth 2 client support with authorization servers, resource servers, access tokens, OAuth 2 login, and RestTemplate.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.