ไคลเอ็นต์ OAuth2 และโฟลว์รหัสการอนุญาต
กำหนดค่าไคลเอ็นต์ OAuth2 เพื่อรับและรีเฟรชโทเค็นผ่านการให้สิทธิ์ด้วยรหัสการอนุญาต
ไคลเอ็นต์ OAuth2 และโฟลว์รหัสการอนุญาต เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why an OAuth2 Client?
When your Spring Boot app needs to act on behalf of a user against an external provider (Google, GitHub, Keycloak, Okta), it becomes an OAuth2 Client.
The client never sees the user's password. Instead it redirects the browser to the provider's authorization endpoint, the user logs in there, and the provider hands back an access_token (and optionally a refresh_token) that the client uses to call protected APIs.
- Authorization Code grant is the recommended browser-based flow.
- Spring Security's
spring-boot-starter-oauth2-clientimplements the entire dance for you.
Adding the Starter
Bring in the OAuth2 client support. In Spring Boot 4 this lives in spring-boot-starter-oauth2-client, which transitively pulls in spring-security-oauth2-client and the JOSE/JWT libraries needed for OIDC.
This Maven dependency is all you need to enable login-with-provider and token acquisition.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>Registering a Client via Properties
The fastest way to register a provider is through application.yml. Spring auto-binds these into a ClientRegistration.
- client-id / client-secret — issued by the provider.
- scope —
openid, profile, emailfor OIDC login. - authorization-grant-type —
authorization_code. - redirect-uri — the callback Spring exposes, usually
{baseUrl}/login/oauth2/code/{registrationId}.
spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: spring-app
client-secret: "${KEYCLOAK_SECRET}"
authorization-grant-type: authorization_code
scope: openid, profile, email
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider:
keycloak:
issuer-uri: https://auth.example.com/realms/demoIssuer Discovery vs. Manual Endpoints
For OIDC providers, setting issuer-uri lets Spring fetch the /.well-known/openid-configuration document at startup and auto-discover the authorization, token, JWK set, and userinfo endpoints.
For plain OAuth2 providers without discovery (e.g. classic GitHub), you must specify the endpoints yourself.
spring:
security:
oauth2:
client:
provider:
github:
authorization-uri: https://github.com/login/oauth/authorize
token-uri: https://github.com/login/oauth/access_token
user-info-uri: https://api.github.com/user
user-name-attribute: idEnabling oauth2Login in SecurityFilterChain
Wire the flow into your SecurityFilterChain. Calling oauth2Login() activates the full Authorization Code flow: unauthenticated requests get redirected to the provider, and the callback is handled automatically.
This is framework configuration, not a standalone program.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/error").permitAll()
.anyRequest().authenticated())
.oauth2Login(Customizer.withDefaults());
return http.build();
}
}The Authorization Code Flow Step by Step
Once oauth2Login() is active, here is what happens behind the scenes:
- 1. User hits a protected URL; Spring redirects the browser to
/oauth2/authorization/{registrationId}. - 2. Spring sends the browser to the provider's authorization endpoint with
response_type=code,state, and a PKCEcode_challenge. - 3. The user authenticates and consents at the provider.
- 4. The provider redirects back to
/login/oauth2/code/{registrationId}carrying a one-time authorization code. - 5. Spring exchanges that code (server-to-server) at the token endpoint for tokens.
The browser never sees the access token in step 5 — it's a back-channel call.
Accessing the Authorized Client and Token
After login, the access token is stored in an OAuth2AuthorizedClient. Inject it with the @RegisteredOAuth2AuthorizedClient argument resolver to read the token your app obtained.
This token is what you attach when calling the downstream resource server.
@RestController
public class ApiController {
@GetMapping("/token")
public String token(
@RegisteredOAuth2AuthorizedClient("keycloak")
OAuth2AuthorizedClient client) {
OAuth2AccessToken accessToken = client.getAccessToken();
return "type=" + accessToken.getTokenType().getValue()
+ " expires=" + accessToken.getExpiresAt();
}
}Calling APIs with RestClient and the Token
Spring Boot 4 favors RestClient. Configure it with the OAuth2ClientHttpRequestInterceptor so it automatically attaches the bearer token from the authorized client (and refreshes it when needed).
- The interceptor reads the registration id from the request attributes.
- No manual
Authorizationheader building required.
@Bean
RestClient restClient(OAuth2AuthorizedClientManager manager) {
OAuth2ClientHttpRequestInterceptor interceptor =
new OAuth2ClientHttpRequestInterceptor(manager);
interceptor.setPrincipalResolver(
new SecurityContextHolderPrincipalResolver());
return RestClient.builder()
.requestInterceptor(interceptor)
.build();
}The Authorized Client Manager
The OAuth2AuthorizedClientManager is the engine that obtains, caches, and refreshes tokens. You configure a provider chain describing which grants it supports.
Enabling refreshToken() here is what makes silent token renewal possible when an access token expires.
@Bean
OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clients,
OAuth2AuthorizedClientRepository authorizedClients) {
OAuth2AuthorizedClientProvider provider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build();
DefaultOAuth2AuthorizedClientManager manager =
new DefaultOAuth2AuthorizedClientManager(clients, authorizedClients);
manager.setAuthorizedClientProvider(provider);
return manager;
}How Refresh Works
To refresh tokens, two things must be true:
- The provider issued a
refresh_token— this typically requires theoffline_accessscope (Keycloak) or an offline grant. - The access token is expired (or within the configured clock skew) when the manager is next asked for the client.
When you call the API through a token-aware RestClient, the RefreshTokenOAuth2AuthorizedClientProvider detects expiry, posts grant_type=refresh_token to the token endpoint, and transparently swaps in the new access token. No user redirect is needed.
spring:
security:
oauth2:
client:
registration:
keycloak:
scope: openid, profile, offline_access
authorization-grant-type: authorization_codeModeling Token Expiry in Plain Java
The refresh decision boils down to comparing an expiry Instant against now, allowing for a clock-skew buffer. Here is that core logic as a complete standalone program you can run to see when a refresh would trigger.
import java.time.Duration;
import java.time.Instant;
public class Main {
static boolean shouldRefresh(Instant expiresAt, Instant now, Duration skew) {
return expiresAt == null || now.isAfter(expiresAt.minus(skew));
}
public static void main(String[] args) {
Instant now = Instant.parse("2026-01-01T10:00:00Z");
Duration skew = Duration.ofSeconds(60);
Instant valid = now.plusSeconds(300); // 5 min left
Instant nearly = now.plusSeconds(30); // inside skew window
Instant expired = now.minusSeconds(10);
System.out.println("valid -> refresh? " + shouldRefresh(valid, now, skew));
System.out.println("nearly -> refresh? " + shouldRefresh(nearly, now, skew));
System.out.println("expired-> refresh? " + shouldRefresh(expired, now, skew));
}
}Quick Check
You configured oauth2Login() and call a downstream API through a token-aware RestClient. The access token expires after 5 minutes, but users stay on the page for 30 minutes without re-authenticating. What single change most directly enables silent token renewal without sending the user back to the login page?
Recap
You configured Spring Boot 4 as an OAuth2 client driving the Authorization Code flow:
- Starter:
spring-boot-starter-oauth2-clientenables the flow. - Registration: client-id/secret,
authorization_codegrant, scopes, and aredirect-uri; OIDC providers auto-discover endpoints viaissuer-uri. - Activation:
oauth2Login()performs the redirect, PKCE code exchange, and callback handling. - Using tokens: inject
@RegisteredOAuth2AuthorizedClientor call APIs via a token-awareRestClientbacked by anOAuth2AuthorizedClientManager. - Refresh: request a refresh-capable scope and build the manager with
.refreshToken()so expired access tokens renew silently viagrant_type=refresh_token.
คำถามที่พบบ่อย
บทเรียน “ไคลเอ็นต์ OAuth2 และโฟลว์รหัสการอนุญาต” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ไคลเอ็นต์ OAuth2 และโฟลว์รหัสการอนุญาต” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ไคลเอ็นต์ OAuth2 และโฟลว์รหัสการอนุญาต”
กำหนดค่าไคลเอ็นต์ OAuth2 เพื่อรับและรีเฟรชโทเค็นผ่านการให้สิทธิ์ด้วยรหัสการอนุญาต คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “ไคลเอ็นต์ OAuth2 และโฟลว์รหัสการอนุญาต” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การตรวจสอบ JWT และข้อมูลอ้างสิทธิ์ของเซิร์ฟเวอร์ทรัพยากร
- ไคลเอ็นต์ OAuth2 และโฟลว์รหัสการอนุญาต
- การรักษาความปลอดภัยเมธอดด้วย SpEL และผู้ลงคะแนนแบบกำหนดเอง
- การตรวจสอบโทเค็นแบบทึบแสงและการแลกเปลี่ยนโทเค็น