로그인/로그아웃 - Spring Security

minjjai·2022년 10월 8일
0
post-thumbnail

이번 글에서는 저번 글에 이어서 Spring Security를 이용해 로그인/로그아웃 기능을 구현해 보려고 한다.

SecurityConfig.java 파일

전 글에서의 시큐리티 설정파일은 다음과 같다.
로그인이 되어있지 않은 상태에서도 모든 페이지에 접근할 수 있도록 설정을 해주었다.

@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>

sec:authorize="isAnonymous()"

  • 로그아웃 상태일 때 해당 엘리먼트를 표시한다.

sec:authorize="isAuthenticated()"

  • 로그인 상태일 때 해당 엘리먼트를 표시한다.

URL요청별 권한 설정

예시 코드

@Controller
public class HomeController {
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/page1")
    public String page1() {
        return "page1";
    }
}

@PreAuthorize("isAuthenticated()")

  • 로그인 상태에서 접근가능한 url 요청

간단히 설명하자면, 현재 SecurityConfig파일의 설정에 의해서 모든 페이지의 접근이 가능하다.
위와 같이 @PreAuthorize("isAuthenticated()")를 달아주면 /page1으로의 요청은 로그인 상태에서만 접근할 수 있도록 설정할 수 있다.

profile
BackEnd Developer

0개의 댓글