이번 글에서는 저번 글에 이어서 Spring Security를 이용해 로그인/로그아웃 기능을 구현해 보려고 한다.
전 글에서의 시큐리티 설정파일은 다음과 같다.
로그인이 되어있지 않은 상태에서도 모든 페이지에 접근할 수 있도록 설정을 해주었다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll()
;
return http.build();
}
}
로그인 설정은 간단히 다음과 같이 해주면 된다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll()
.and()
.formLogin()
.loginPage("/user/login") //로그인 url
.defaultSuccessUrl("/") //로그인 성공시 이동할 url
;
return http.build();
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll()
.and()
.formLogin()
.loginPage("/user/login") //로그인 url
.defaultSuccessUrl("/") //로그인 성공시 이동할 url
.and()
.logout()
//로그아웃 url
.logoutRequestMatcher(new AntPathRequestMatcher("/user/logout"))
.logoutSuccessUrl("/") //로그아웃 성공시 이동할 url
.invalidateHttpSession(true) //로그아웃시 생성된 세션 삭제 활성화
;
return http.build();
}
}
보통 웹페이지의 헤더에 로그인 상태에서는 로그아웃 버튼이 표시되고, 로그아웃 상태에서는 로그인 버튼이 표시되는 것을 볼 수 있다.
html파일의 헤더에 다음과 같이 코드를 작성해주면 된다.
<a sec:authorize="isAnonymous()" th:href="@{/user/login}">로그인</a>
<a sec:authorize="isAuthenticated()" th:href="@{/user/logout}">로그아웃</a>
@Controller
public class HomeController {
@PreAuthorize("isAuthenticated()")
@GetMapping("/page1")
public String page1() {
return "page1";
}
}
간단히 설명하자면, 현재 SecurityConfig파일의 설정에 의해서 모든 페이지의 접근이 가능하다.
위와 같이 @PreAuthorize("isAuthenticated()")를 달아주면 /page1으로의 요청은 로그인 상태에서만 접근할 수 있도록 설정할 수 있다.