[ Spring Security ] Anonymous Authentication
AnonymousAuthenticationToken
This is what we mean by anonymous authentication. Note that there is no real conceptual difference between a user who is “
anonymously authenticated
” and an unauthenticated user
.역할
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (SecurityContextHolder.getContext().getAuthentication() == null) { Authentication authentication = createAuthentication((HttpServletRequest) req); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); SecurityContextHolder.setContext(context); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.of(() -> "Set SecurityContextHolder to " + SecurityContextHolder.getContext().getAuthentication())); } else { this.logger.debug("Set SecurityContextHolder to anonymous SecurityContext"); } } else { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.of(() -> "Did not set SecurityContextHolder since already authenticated " + SecurityContextHolder.getContext().getAuthentication())); } } chain.doFilter(req, res); }
- SecurityContextHolder.getContext( ).getAuthentication( ) == null 일 때,
AnonymousAuthenticationToken
을 만들어주는 역할을 함 AnonymousAuthenticationToken
토큰 만듦- 빈 SecurityContext를 만듦
- 해당 context에
AnonymousAuthenticationToken
토큰 할당
설정
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/me").hasAnyRole("USER", "ADMIN") .anyRequest().permitAll() .and() .formLogin() .defaultSuccessUrl("/") .permitAll() .and() .logout() .logoutSuccessUrl("/") .and() .rememberMe().tokenValiditySeconds(300) .and() .anonymous() .principal("thisIsAnonymousUser") .authorities("ROLE_ANONYMOUS", "ROLE_UNKNOWN"); }
- 이런 설정이 있긴 하지만 사용 사실 거의 안함