모든 자료는 인프런의 스프링 시큐리티 - Spring Boot 기반으로 개발하는 Spring Security 강의를 참고하였습니다!!!
인증 API - 스프링 시큐리티의 의존성 추가
인증 API - 사용자 정의 보안 기능 구현
❌ 시작하기에 앞서 강의에는 WebsecurityConfigurerAdapter를 상속받아 사용하지만 스프링 시큐리티 5.7에서는 더이상 지원하지 않기 때문에 상속이 아닌 bean으로 등록하여 컨테이너가 관리할 수 있도록 사용한다.
변경 전 : 메서드를 오버라이딩해서 설정을 하고 클래스 내부에 설정 정보를 저장
변경 후 : bean으로 등록, 반환 값이 void에서 특정 타입을 리턴하도록 변경 (http.build())
예시코드
package com.test.kakaogamematch.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
// 이제 WebConfigurerAdapter를 상속받아 configure를 오버라이딩하지 않고 bean으로 관리
public class SecurityConfig {
// 변경 전 : configure 오버라이딩
/*@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring().anyRequest();
//.requestMatchers("/h2-console/**") // 인가 처리를 무시하는 url 설정
}
*/
// 변경 전 : configure 오버라이딩
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests() // 요청에 대한 보안검사 시작
.anyRequest().authenticated(); // 어떤 요청에도 인증 받음 (인가 정책)
http
.formLogin(); // 기본적으로 form 로그인 방식으로 인증 설정
return http.build();
}
}
인증 API - Form 인증
.loginPage("/login.html")
: 사용자 정의 로그인 페이지
.defaultSuccessUrl("/home")
: 로그인 성공 후 이동 페이지
.failureUrl()
: 로그인 실패 후 이동 페이지
.usernameParameter
: 아이디 파라미터명 설정
.passwordParameter
: 패스워드 파라미터명 설정
.loginProcessingUrl()
: 로그인 Form Action Url
.successHandler(loginSuccessHandler())
: 로그인 성공 후 핸들러
.failureHandler(loginFailureHandler())
: 로그인 실패 후 핸들러
http
.formLogin() // 기본적으로 form 로그인 방식으로 인증 설정
//.loginPage("/loginPage") // 내가 설정한 로그인 페이지
.defaultSuccessUrl("/")
.failureUrl("/login")
.usernameParameter("userId")
.passwordParameter("passwd")
.loginProcessingUrl("/login_proc")
// .successHandler(new AuthenticationSuccessHandler() {
// @Override
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// System.out.println("authentication : "+authentication.getName());
// response.sendRedirect("/");
// }
// })
// .failureHandler(new AuthenticationFailureHandler() {
// @Override
// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// System.out.println("exception : "+exception.getMessage());
// response.sendRedirect("/login");
// }
// })
.permitAll(); // loginPage에 접근하는 사용자들은 인증 제외
인증 API - Login Form 인증(2)
인증 API - Logout
1. Client가 로그아웃 시도
2. 스프링 시큐리티가 그 요청을 받음
2-1. 세션 무효화
2-2. 인증 토큰(인증 객체), 인증 토큰이 저장돼있는 SecurityContext 삭제
2-3. 쿠키정보 삭제
3. 로그인 페이지로 리다이렉트
.logoutUrl()
: 로그아웃 처리 URL
.logoutSuccessUrl()
: 로그아웃 성공 후 이동 페이지
.deleteCookies("쿠키명", "쿠키명")
: 로그아웃 후 쿠키 삭제
.addLogoutHandler(logoutHandler())
: 스프링 시큐리티가 기본적으로 제공하는 로그아웃 핸들러 구현체에서 하는 처리 외에 별도로 어떠한 처리를 하고 싶을 때 사용
.logoutSuccessHandler(logoutSuccessHandler())
: 로그아웃이 성공적으로 수행됐을 때 실행될 핸들러
http
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.addLogoutHandler(new LogoutHandler() {
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
HttpSession session = request.getSession();
session.invalidate();
}
})
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.sendRedirect("/login");
};
})
.deleteCookies("remember-me");
1. logout 필터가 요청 받음
2. AntPathRequestMatcher가 검사
3. Authentication가 인증객체 담고 있는 객체를 꺼내와서 핸들러에 전달
4. SecurityContextLogoutHandler가 세션을 무효화하고 퀴를 삭제하고 SecurityContext를 삭제함, 인증 객체도 null로 처리