티스토리 뷰

1. HTTP Basic 인증

http.httpBasic(Customizer.withDefaults());
  • 클라이언트에서 Header를 통해 Authorization: Basic base64(id:pw) 형태로 요청
  • BasicAuthenticationFilter 필터가 SecurityFilterChain에 추가되어 (Basic Authentication 활성화)
  • Basic Authentication 인증 방식
    - Authorization 헤더에 username:password ID/PW 인증 정보를 Base64 인코딩 후 전송
    - Authorization 헤더 형태 :: Authorization: Basic {base64(usename:password)}

1.1 처리 흐름

1. BasicAuthenticationFilter 에서 Authorization 헤더 내 ID/PW 인증 정보를 디코딩하여
2. UsernamePasswordAuthenticationProvider 에 전달하여 ID/PW 인증 정보와 일치하는 계정확인
3. UserDetailsService 구현클래스에서 DAO(UserRepository) 통해 UserDetails 조회 및 일치확인
4. 일치 완료가 확인되었을 시 반환된 Authentication 을 SecurityContextHolder 내 저장


1.2 특징

 

  • 매우 간단한 인증 방식
  • 매 요청마다 ID/PW 전송 (재사용 불가)
  • HTTPS 필수 (Base64는 암호화 아님)
  • 주로 내부 시스템, 테스트 환경, 서버 간 통신에 사용

1.3 Spring Security 인증 방식 비교 formLogin() vs httpBasic()

- httpBasic() :: 로그인 페이지 통해 FORM 으로 ID/PW 보내어 인증
- formLogin() :: 로그인 페이지 없이 Authorization Header 에 ID/PW 보내어 인증

항목 formLogin() httpBasic()
방식 Form Submit Header 전송 (Base64)
필터 UsernamePasswordAuthenticationFilter BasicAuthenticationFilter
저장소 - HttpSession (영속적)
- HttpSessionSecurityContextRepository
  → HttpSession에 SecurityContext 저장
- HttpServletRequest (비영속)
- RequestAttributeSecurityContextRepository
   → HttpServletRequest에만 저장
상태 Stateful Stateless -> 유지되지 않음 (매 요청마다 인증 필요)
성공처리 AuthenticationSuccessHandler 없음
실패처리 AuthenticationFailureHandler BasicAuthenticationEntryPoint에서
401 응답 및 WWW-Authenticate 헤더 반환
주 사용처 일반 웹 로그인 API, 서버 간 인증 등

1.4 Basic Authentication에서 Realm

:: 하나의 도메인 내에서도 페이지나 리소스를 그룹화하여,
:: 각 그룹마다 서로 다른 인증 정보(ID/PW) 를 요구하도록 분리한 인증 영역(Authentication Domain)

// 서버의 응답 방식 (Basic 인증 기준)

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="A Group" // 브라우저나 클라이언트에게 어떤 Realm의 자격 증명을 요구하는지 명시

 


- 사용 예시 (Spring Security + Basic Auth)

http
  .httpBasic(withDefaults())  // Basic 인증 사용
  .authorizeHttpRequests(auth -> auth
      .requestMatchers("/admin/**").hasRole("ADMIN")  // ADMIN Realm
      .requestMatchers("/user/**").hasRole("USER")    // USER Realm
      .anyRequest().authenticated()
  );
// Spring Security는 BasicAuthenticationEntryPoint를 통해 Realm 명을 설정 가능
@Bean
public BasicAuthenticationEntryPoint basicAuthEntryPoint() {
    BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint();
    entryPoint.setRealmName("Admin Group");
    return entryPoint;
}

2. Authorization 헤더를 통한 인증 방식 비교 (Basic 인증과 Bearer 인증)

2.1 Basic 인증

:: username:password를 Base64로 인코딩한 문자열을 인증 정보로 사용하는 방식

Authorization: Basic <base64(username:password)>
항목 설명
형식 username:password 문자열을 Base64로 인코딩하여 전달
예시 Authorization: Basic dXNlcjpwYXNz (user:pass)
처리 방식 매 요청마다 서버는 이 정보를 디코딩하여 유효한 사용자 인증 여부를 확인
장점 - 매우 간단한 구현- 별도의 인증 서버나 토큰 발급 시스템 불필요
단점 - Base64는 암호화가 아님 (디코딩 가능)
- HTTPS 필수 (평문 노출 위험)
- 매 요청마다 ID/PW 전송 → 성능·보안 부담
예시 내부 API 간 인증, 단순 테스트용 서비스 등

2.2 Bearer 인증 (토큰 기반 인증)

:: 사용자가 로그인 후 발급받은 Access Token을 인증 수단으로 사용하는 방식 

:: 주로 OAuth2나 JWT 기반 시스템에서 사용

Authorization: Bearer <access_token>
항목 설명
형식 <access_token> = 클라이언트가 로그인/인증 후 발급받은 토큰
예시 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
처리 방식 서버는 이 토큰을 검증하여 인증된 사용자임을 판단
토큰 종류 - JWT (JSON Web Token): 자체 인코딩된 구조, 정보 내장
- Opaque Token: 정보 없음, 별도 저장소 확인 필요
장점 - ID/PW 직접 노출하지 않음
- 재사용 가능, 인증 이후 여러 API 호출 가능
- 만료 기간, 갱신 토큰(Refresh Token) 등 보안 강화
- OAuth2 및 OpenID Connect와 연동 쉬움
단점 - 토큰 유출 시 보안 취약 (특히 만료 전까지)
- 토큰 저장소, 만료 관리 등 구현 복잡도 증가
예시 REST API, 모바일 앱, SPA(프론트/백 분리) 인증 등

2.3 formLogin() vs httpBasic()

1. 공통점

:: Authorization 헤더 기반 인증

Authorization: <type> <credentials>
// <type>: 인증 방식 (예: Basic, Bearer)
// <credentials>: 인증 정보 (ID/PW or Access Token)

2. 차이

항목 Basic 인증 Bearer 인증
인증 정보 ID/PW Access Token
헤더 예시 Authorization: Basic dXNlcjpwYXNz Authorization: Bearer eyJ...
보안 방식 Base64 (암호화 아님) → HTTPS 필수 토큰 검증 (JWT 또는 Opaque)
서버 상태 무상태 가능하지만 일반적으로 ID/PW 필요 → 상태 보존 필요 무상태 (stateless) 인증에 최적화
세션 필요 여부 보통 세션 기반 세션 불필요 (Stateless API에 적합)
재사용성 매번 ID/PW 재전송 토큰 유효기간 동안 재사용 가능
갱신 없음 가능 (Refresh Token 활용)
사용 사례 간단한 서비스, 서버 간 통신 OAuth2 인증, 모바일 앱, REST API 등
  • Basic 인증
    :: 보통 인증서버 없이 빠르게 인증 시스템을 붙일 때 사용
    :: 반드시 HTTPS 환경에서만 사용해야 함(보안 이슈..)

  • Bearer 인증
    :: SPA(React/Vue), 모바일 앱, 외부 공개 API 등에서 거의 표준
    :: JWT 사용 시 추가적인 정보(roles, userId 등)를 토큰에 담아 무상태 인증 가능

3. OAuth2 로그인

http.oauth2Login(oauth -> oauth
    .loginPage("/oauth2/authorization/kakao")
    .userInfoEndpoint(userInfo -> userInfo
        .userService(customOAuth2UserService))
);
  • 외부 인증 서버와 연동하는 경우 (카카오, 네이버, 구글)
  • OAuth2UserService를 통해 사용자 정보를 받아 인증 완료

참고

ASAC 수업자료

https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html

 

Cross Site Request Forgery (CSRF) :: Spring Security

To handle an AccessDeniedException such as InvalidCsrfTokenException, you can configure Spring Security to handle these exceptions in any way you like. For example, you can configure a custom access denied page using the following configuration: Configure

docs.spring.io

https://stackoverflow.com/questions/76349670/difference-between-entrypoint-and-handler-in-spring-security/76351171#76351171

 

https://docs.tosspayments.com/blog/everything-about-basic-bearer-auth

 

Basic 인증과 Bearer 인증의 모든 것 | 토스페이먼츠 개발자센터

비밀번호로 이메일 계정의 권한을 확인하는 것 처럼, HTTP 인증으로 서버에 접근하는 클라이언트의 권한을 확인해요.

docs.tosspayments.com

 

https://www.linkedin.com/pulse/basic-authentication-vs-bearer-token-choosing-right-your-chopade-rqf7f/

 

Basic Authentication vs. Bearer Token : Choosing the right authentication method for Your Application

In web development, security is very important. There are many ways to keep application resources secure, and authentication plays a significant role in that aspect.

www.linkedin.com

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함