0Pricing
Spring Security 6 & JWT Authentication · 강의

인증 오류와 진입점 처리하기

AuthenticationEntryPoint와 AccessDeniedHandler를 사용해 JWT로 보호되는 Spring 애플리케이션이 토큰 누락, 유효하지 않은 토큰, 만료된 토큰에 응답하는 방식을 사용자 지정해 보세요.

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

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

Two Kinds of Security Failure

Spring Security distinguishes two failures:

  • Authentication failure (401): the user is not identified — missing or bad token
  • Authorization failure (403): the user is known but lacks permission

Each is handled by a different component.

The Default Behavior

Out of the box, a JWT app without a custom handler may redirect to a login page or return an HTML error. For a stateless API you usually want a clean JSON 401 instead.

AuthenticationEntryPoint

The AuthenticationEntryPoint is invoked when an unauthenticated user hits a protected endpoint. Implement commence to write your own response.

public interface AuthenticationEntryPoint {
    void commence(HttpServletRequest req,
                  HttpServletResponse res,
                  AuthenticationException ex);
}

Returning a JSON 401

Here the entry point sets a 401 status and writes a small JSON body, ideal for SPA and mobile clients.

res.setStatus(401);
res.setContentType('application/json');
res.getWriter().write("{\"error\":\"Unauthorized\"}");

AccessDeniedHandler

When an authenticated user lacks the required role, the AccessDeniedHandler runs. Implement handle to send a 403 response.

public interface AccessDeniedHandler {
    void handle(HttpServletRequest req,
                HttpServletResponse res,
                AccessDeniedException ex);
}

Returning a JSON 403

The denied handler mirrors the entry point but uses status 403 to signal a permission problem rather than a missing identity.

res.setStatus(403);
res.setContentType('application/json');
res.getWriter().write("{\"error\":\"Forbidden\"}");

Wiring Handlers into HttpSecurity

Register both handlers in your security configuration through exceptionHandling.

http.exceptionHandling(ex -> ex
    .authenticationEntryPoint(jwtEntryPoint)
    .accessDeniedHandler(jwtDeniedHandler));

Errors Inside the JWT Filter

If your JWT filter detects an expired or malformed token, do not throw a raw exception. Instead set a request attribute and let the entry point produce a consistent response.

catch (ExpiredJwtException e) {
    request.setAttribute('jwt_error', 'expired');
    filterChain.doFilter(request, response);
}

Including Helpful Details

A good error body helps clients react. Include a machine-readable code and a timestamp, but never leak internal stack traces or secrets.

res.getWriter().write(
  "{\"error\":\"token_expired\",\"status\":401}");

Consistent Error Shape

Keep every security error in the same JSON shape as your other API errors. Consistency lets the frontend handle 401, 403, and 500 with one error pipeline.

Testing the Handlers

Use MockMvc to confirm an unauthenticated request returns 401 and an under-privileged request returns 403 with the expected JSON.

mockMvc.perform(get('/api/secure'))
    .andExpect(status().isUnauthorized())
    .andExpect(jsonPath('$.error').value('Unauthorized'));

Quick Check

Test your understanding of security error handling.

Recap

You learned to customize JWT security errors:

  • AuthenticationEntryPoint handles 401 (unauthenticated)
  • AccessDeniedHandler handles 403 (forbidden)
  • Wire both via exceptionHandling
  • Return consistent JSON and never leak internals

Clear, predictable error responses make your secured API far easier to consume.

자주 묻는 질문

“인증 오류와 진입점 처리하기” 강의는 무료인가요?

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

“인증 오류와 진입점 처리하기”에서 뭘 배우나요?

AuthenticationEntryPoint와 AccessDeniedHandler를 사용해 JWT로 보호되는 Spring 애플리케이션이 토큰 누락, 유효하지 않은 토큰, 만료된 토큰에 응답하는 방식을 사용자 지정해 보세요. 브라우저에서 직접 실행하는 실습 코드로 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. JWT 인증 흐름 설계하기
  2. 사용자 지정 JWT 필터 구현하기
  3. AuthenticationManager 및 Provider 통합
  4. 인증 오류와 진입점 처리하기
← Spring Security 6 & JWT Authentication(으)로 돌아가기