HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🤩
개발
/
🔐
Spring Security
/
🖇️
Custom Filter 이용 ( addFilterAt )
🖇️

Custom Filter 이용 ( addFilterAt )

CustomFilter이용

public CustomLoginFilter(AuthenticationManager authenticationManager){ super(authenticationManager); } @Override protected void configure(HttpSecurity http) throws Exception { CustomLoginFilter filter = new CustomLoginFilter(authenticationManager()); http .authorizeRequests(request-> request.antMatchers("/", "/login").permitAll() .anyRequest().authenticated() ) // .formLogin(login -> login.loginPage("/login").permitAll() // .defaultSuccessUrl("/", false) // .failureUrl("/login-error")) .addFilterAt(filter, UsernamePasswordAuthenticationFilter.class) .logout(logout -> logout.logoutSuccessUrl("/")) .exceptionHandling(e -> e.accessDeniedPage("/access-denied")) ; } public class CustomLoginFilter extends UsernamePasswordAuthenticationFilter { public CustomLoginFilter(AuthenticationManager authenticationManager){ super(authenticationManager); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String username = obtainUsername(request); username = (username != null) ? username : ""; username = username.trim(); String password = obtainPassword(request); password = (password != null) ? password : ""; String type = request.getParameter("type"); if (type == null || !type.equals("teacher")){ StudentAuthenticationToken token = StudentAuthenticationToken.builder(). credentials(username).build(); return this.getAuthenticationManager().authenticate(token); } else{ TeachertAuthenticationToken token = TeachertAuthenticationToken.builder().credentials(username).build(); return this.getAuthenticationManager().authenticate(token); } } }
  • addFilterAt 함수를 이용하여 UsernamePasswordAuthenticationFilter 의 자리에 CustomFilter를 대체해 넣을 수 있음
  • 그러나 이때 formLogin 뒤에 붙어있는 defaultSuccessUrl("/", false)과 failureUrl("/login-error") 또한 코멘트 되기 때문에 실패와 성공 시에 대한 처리가 안되게 됨. CustomFilter쪽에 이를 일일히 구현해 주어야 함