Spring Security에서는 익명 인증이라는 개념이 존재하는데, 익명 인증이란 인증 받지 않은 사용자를 의미한다.
이게 말이 좀 헷갈릴수 있지만 우리는 흔히 인증받은 사용자, 인증받지 않은 사용자 이렇게 구분해서 생각하지만 Spring Security는 인증받은 사용자, 익명으로 인증받은 사용자(=인증받지 않은 사용자) 로 구분한다.
그 이유는 SecurityContextHolder가 항상 Authentication 객체를 포함하고 null을 포함하지 않는다는 규칙을 세우면 클래스를 더 견고하게 작성할 수 있기 때문인데, 특정 자원에 요청을 보내면 이 요청이 인증된 사용자의 요청인지 익명으로 인증된 사용자의 요청인지 객체로 구분을 할 수 있다는 의미이다.
anonymous config 설정은 대부분 그냥 default로 두고 따로 설정해줘야 할건 없지만 나는 테스트를 위해 몇가지 설정을 해주었다.
@EnableWebSecurity
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/anonymous").hasRole("GUEST") // /anonymous 의 접근은 GUEST 권한을 가진 사용자만 가능하다.
.requestMatchers("/anonymousContext").permitAll() // /anonymousContext 의 접근은 모두 가능하다.
.anyRequest().authenticated());
http.formLogin(Customizer.withDefaults());
http.anonymous(anonymous -> anonymous
.principal("guest")
.authorities("ROLE_GUEST"));
return http.build();
}
}
controller는 아래와 같다.
@RestController
public class IndexController {
@GetMapping("/")
public String index(){
return "index";
}
@GetMapping("/anonymous")
public String anonymous(){
return "anonymous";
}
// 익명 요청에서 Authentication 객체를 얻고싶으면 @CurrentSecurityContext를 사용한다.
@GetMapping("/anonymousContext")
public void anonymousContext(@CurrentSecurityContext SecurityContext context){
System.out.println("context.getAuthentication().isAuthenticated() : " + context.getAuthentication().isAuthenticated());
System.out.println("context.getAuthentication().getAuthorities() : " + context.getAuthentication().getAuthorities());
System.out.println("context.getAuthentication().getName() : " + context.getAuthentication().getName());
}
}
이 상태로 테스트를 진행하면
📌 익명으로 인증된 사용자(/anonymous 접근시)

📌 인증된 사용자 (/anonymous 접근시)

📌 익명으로 인증된 사용자와 익명으로 인증된 사용자 console 비교 (/anonymousContext 접근시)

위의 콘솔 결과로도 알 수 있듯이 인증된 사용자와 익명으로 인증된 사용자는 모두 isAuthenticated가 true인 것을 알 수 있다.
'Spring Security' 카테고리의 다른 글
| [Spring Security] logout (0) | 2024.05.12 |
|---|---|
| [Spring Security] RememberMe 인증 (0) | 2024.05.09 |
| [Spring Security] 사용자 인증 메커니즘 (Form) (0) | 2024.05.07 |
| [Spring Security] 로그인 관련 security config 기본 설정 (Form) (0) | 2024.05.06 |