범위 및 클레임 적용
수신되는 JWT의 특정 범위와 클레임을 적용하여 API의 각 부분에 대한 접근을 제어합니다.
범위 및 클레임 적용은(는) CoddyKit의 무료 Spring Security 6 & JWT Authentication 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Security 6 & JWT Authentication 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Authorization with Scopes & Claims
Welcome! In this lesson, we'll learn how to control access to your API endpoints using scopes and claims in an OAuth2 Resource Server.
These are crucial components of a JSON Web Token (JWT) that tell your server who the user is and what they are allowed to do.
Understanding OAuth2 Scopes
Think of scopes as specific permissions or access rights that a client application requests on behalf of a user.
- They are defined by the Resource Server.
- Examples:
read,write,profile,email. - When a user grants permission, these scopes are included in the issued JWT.
They define the "what" a client can do within the API.
JWT Claims Explained
Claims are pieces of information about the user or the token itself, stored as key-value pairs inside the JWT payload.
- Standard Claims:
sub(subject/user ID),exp(expiration time),iss(issuer). - Custom Claims: You can add your own data, like
role,department, oruser_id.
Claims provide context about "who" the user is and their specific attributes.
Spring Security & Scopes Mapping
When Spring Security processes an incoming JWT, it automatically extracts the scopes from the token.
It then converts these scopes into Spring Security authorities by prefixing them with SCOPE_.
For example, a scope read becomes an authority SCOPE_read, which can then be checked using expression language.
@PreAuthorize for Scopes
You can enforce scope-based authorization on your API methods using Spring Security's @PreAuthorize annotation.
This annotation allows you to define SpEL (Spring Expression Language) expressions that must evaluate to true for the method to be executed.
Use hasAuthority('SCOPE_<your_scope>') to check for a specific scope.
Scope Protection Demo
Let's see how to protect an endpoint using the SCOPE_read authority. Only tokens with the 'read' scope can access this resource.
package com.coddykit.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.access.prepost.PreAuthorize;
@SpringBootApplication
@EnableMethodSecurity // Enable @PreAuthorize
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
@Configuration
class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> {}))
.csrf(csrf -> csrf.disable()); // For simplicity in demo
return http.build();
}
}
@RestController
class DataController {
@GetMapping("/data/public")
public String getPublicData() {
return "This is public data (authenticated)";
}
@GetMapping("/data/secret")
@PreAuthorize("hasAuthority('SCOPE_read')")
public String getSecretData() {
return "This is secret data, requires 'read' scope!";
}
}Leveraging Custom Claims
While scopes are great for general permissions, custom claims allow for more fine-grained or context-specific authorization.
For example, you might have a role claim with values like ADMIN or USER, or a department_id claim.
These claims are directly accessible from the authenticated principal in Spring Security, offering rich contextual data.
@PreAuthorize for Claims
You can also use @PreAuthorize to check for specific claims in the JWT payload.
Spring Security's SpEL allows you to access the authenticated principal's claims directly.
Use expressions like #oauth2.token.claims['role'] == 'ADMIN' or #oauth2.token.claims['department'] == 'IT'.
Claim Protection Demo
Here's an example of an endpoint protected by a custom role claim. Only users with role:ADMIN can access this sensitive data.
package com.coddykit.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.access.prepost.PreAuthorize;
@SpringBootApplication
@EnableMethodSecurity
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
@Configuration
class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> {}))
.csrf(csrf -> csrf.disable());
return http.build();
}
}
@RestController
class AdminController {
@GetMapping("/admin/report")
@PreAuthorize("#oauth2.token.claims['role'] == 'ADMIN'")
public String getAdminReport() {
return "Sensitive admin report data!";
}
@GetMapping("/admin/dashboard")
@PreAuthorize("hasAuthority('SCOPE_admin') and #oauth2.token.claims['department'] == 'IT'")
public String getITAdminDashboard() {
return "IT Department Admin Dashboard!";
}
}Quick Check: Scopes & Claims
Which of the following statements correctly describe the use of scopes and claims in Spring Security for an OAuth2 Resource Server?
Recap: Scopes & Claims
We've covered how scopes and claims are fundamental for authorization in an OAuth2 Resource Server.
- Scopes define broad permissions (e.g.,
read,write). - Claims provide detailed user attributes (e.g.,
role,department). - Both can be enforced using
@PreAuthorizewith SpEL expressions.
Mastering these allows for robust and flexible access control in your APIs!
자주 묻는 질문
“범위 및 클레임 적용” 강의는 무료인가요?
네 — “범위 및 클레임 적용” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Security 6 & JWT Authentication 강의 전체를 잠금 해제할 수 있습니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.
“범위 및 클레임 적용”에서 뭘 배우나요?
수신되는 JWT의 특정 범위와 클레임을 적용하여 API의 각 부분에 대한 접근을 제어합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Security 6 & JWT Authentication을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Security 6 & JWT Authentication을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Security 6 & JWT Authentication은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“범위 및 클레임 적용” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Security 6 & JWT Authentication 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Security 6 & JWT Authentication 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.