본문 바로가기

Spring/spring security

spring security DB를 이용한 로그인 구현 3 ( 로그아웃 하기 ) - 삽질중인 개발자

반응형

- logout -

이 포스팅에서는 로그아웃을 구현한다.

 

 

1. 로그아웃 버튼 만들기

스프링 시큐리티의 기본 로그아웃 url은 POST 메소드의 /logout 이다.

<form action="/logout" method="POST">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    <button type="submit">LOGOUT</button>
</form>

 

2. SecurityConfig.java (이전 포스팅 6번) 에 아래의 코드 추가

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	http
        .authorizeRequests()
        	.antMatchers("/member/**").hasAnyAuthority("MEMBER")
        .and()
        	.formLogin()	//로그인 폼 사용
        		.loginPage("/login")	//커스텀 로그인 페이지
        		.successHandler(customAuthenticationSuccessHandler)
        		.failureHandler(customAuthenticationFailureHandler)
        		.usernameParameter("memberId")	//스프링 시큐리티에서는 username을 기본 아이디 매핑 값으로 사용하는데 이거 쓰면 변경
        		.passwordParameter("memberPassword")	//이건 password를 변경
        		.permitAll()

// 이 아래부분 추가하면 됩니다.

		.and()
        	.logout()	// 로그아웃 사용
        	.logoutSuccessUrl("/")	//로그아웃 시 가지는 페이지
        	.invalidateHttpSession(true)	// 세션 초기화
        	.deleteCookies("JSESSIONID");	//쿠키 삭제
        	
    		
    }

 

3. (생략 가능) customLogoutSuccessHandler.java 구현 

만약 로그아웃 시 특별한 로직이 필요하다면 customLogoutSuccessHandler 를 만들어야 한다.

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;

public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		//여기에 로직 추가
		super.onLogoutSuccess(request, response, authentication);
	}
}

 

 

로그아웃은 그냥 스프링 시큐리티의 기본 기능을 사용하는게 편하다.

 


스프링 시큐리티와 MariaDB를 이용한 로그인 방법

 

Spring security 커스텀 로그인 1 - 개발자 삽질 일기

스프링 시큐리티 스프링 기반의 어플리케이션의 보안(인증과 권한)을 담당하는 프레임워크이다. 스프링 시큐리티를 사용하면 로그인, 로그아웃 그 외의 각종 인증 관련 기능을 간편하게 구현할 수 있다. 개발 환경..

programmer93.tistory.com

 

spring secuirty에서 ajax를 이용하여 로그인 하는 방법

 

Spring security 커스텀 로그인 2 - 개발자 삽질 일기

- AJAX 를 이용한 커스텀 로그인 - 이 포스팅에서는 jQuery Ajax를 이용한 커스텀 로그인 페이지 구현을 할 것이다. 스프링 시큐리티에 기본 로그인 페이지는 로그인 실패시 페이지를 새로고침하고 쿼리스트링(loc..

programmer93.tistory.com

 

반응형