0Pricing
Spring Security 6 & JWT Authentication · 강의

사용자 지정 접근 규칙으로 엔드포인트 보호하기

단순한 역할 확인을 넘어 AuthorizationManager, SpEL 표현식, 요청 매처를 사용해 Spring Security 6에서 사용자 지정 권한 부여 로직을 작성해 보세요.

사용자 지정 접근 규칙으로 엔드포인트 보호하기은(는) CoddyKit의 무료 Spring Security 6 & JWT Authentication 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Security 6 & JWT Authentication 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Custom Access Rules?

Roles and methods cover most cases, but real apps need finer control: only the owner of a resource may edit it, or access depends on the time of day or a feature flag.

Spring Security 6 lets you express these rules declaratively or programmatically.

The authorizeHttpRequests DSL

In Spring Security 6 the modern way to secure URLs is authorizeHttpRequests. Each matcher maps a request pattern to an access rule.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/public/**').permitAll()
    .requestMatchers('/admin/**').hasRole('ADMIN')
    .anyRequest().authenticated());

Matching by HTTP Method

You can scope rules to a specific HTTP method, so reads and writes have different requirements.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers(HttpMethod.GET, '/api/orders/**').authenticated()
    .requestMatchers(HttpMethod.POST, '/api/orders/**').hasRole('MANAGER'));

SpEL with access()

The access() rule takes a Spring Expression Language (SpEL) condition for dynamic logic that plain matchers cannot express.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/reports/**')
    .access(new WebExpressionAuthorizationManager(
        "hasRole('ANALYST') and request.getHeader('X-Region') == 'EU'")));

The AuthorizationManager Interface

For full control, implement AuthorizationManager. It returns an AuthorizationDecision that grants or denies access based on the authentication and the request.

public interface AuthorizationManager<T> {
    AuthorizationDecision check(Supplier<Authentication> auth, T object);
}

Writing a Custom AuthorizationManager

Here is a manager that only allows access during business hours. The supplier gives the current user; the object holds request context.

AuthorizationManager<RequestAuthorizationContext> businessHours =
    (auth, ctx) -> {
        int hour = LocalTime.now().getHour();
        boolean ok = hour >= 9 && hour < 18;
        return new AuthorizationDecision(ok);
    };

Plugging It In

Attach your custom manager to a matcher with access(). Any request to the path is now evaluated by your logic.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/maintenance/**').access(businessHours)
    .anyRequest().authenticated());

Owner-Based Access

A common rule: only the resource owner can modify it. You can read a path variable from the request context to compare against the logged-in user.

AuthorizationManager<RequestAuthorizationContext> ownerOnly =
    (auth, ctx) -> {
        String pathUser = ctx.getVariables().get('userId');
        boolean same = auth.get().getName().equals(pathUser);
        return new AuthorizationDecision(same);
    };

Combining Rules

Spring evaluates matchers top to bottom and stops at the first match. Order matters: put specific rules before broad ones, and always end with a catch-all like anyRequest().

Denying by Default

A secure baseline denies everything not explicitly allowed. Use denyAll() as the final rule when you want a strict allow-list.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/health').permitAll()
    .anyRequest().denyAll());

Testing Access Rules

Verify your rules with @WithMockUser and MockMvc. Assert that authorized users get 200 and unauthorized users get 403.

mockMvc.perform(get('/admin/dashboard'))
    .andExpect(status().isForbidden());

Quick Check

Test your understanding of custom access rules.

Recap

You learned to write custom authorization in Spring Security 6:

  • Use the authorizeHttpRequests DSL with path and method matchers
  • Apply SpEL conditions via access()
  • Implement AuthorizationManager for dynamic, owner-based, or time-based rules
  • Order matters; end with a catch-all and prefer deny-by-default

These tools let you enforce business-specific security policies precisely.

자주 묻는 질문

“사용자 지정 접근 규칙으로 엔드포인트 보호하기” 강의는 무료인가요?

네 — “사용자 지정 접근 규칙으로 엔드포인트 보호하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Security 6 & JWT Authentication 강의 전체를 잠금 해제할 수 있습니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.

“사용자 지정 접근 규칙으로 엔드포인트 보호하기”에서 뭘 배우나요?

단순한 역할 확인을 넘어 AuthorizationManager, SpEL 표현식, 요청 매처를 사용해 Spring Security 6에서 사용자 지정 권한 부여 로직을 작성해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Spring Security 6 & JWT Authentication을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Security 6 & JWT Authentication을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Security 6 & JWT Authentication은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“사용자 지정 접근 규칙으로 엔드포인트 보호하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Security 6 & JWT Authentication 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Security 6 & JWT Authentication 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 역할 기반 접근 제어(RBAC)
  2. 주석을 사용한 메서드 수준 보안
  3. HttpSecurity 구성 심층 학습
  4. 사용자 지정 접근 규칙으로 엔드포인트 보호하기
← Spring Security 6 & JWT Authentication(으)로 돌아가기