Spring-Security-1

akanana·2023년 2월 16일
0

개인공부

목록 보기
30/30

목표

  • 스프링 세큐리티 로그인/로그아웃 설정

설정파일 구성

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        http.csrf().disable();

        return http.build();
    }
}

위 코드에서 반환된 SecurityFilterChain을 통하여 필터를 관리 할 수 있다

csrf는 왜 disable시키나요?
csrf

csrfCross Site Request Forgery의 약자로, 사용자가 의도하지 않은 위조요청을 보내는거을 의미한다
하지만 해당 환경에서 spring 프로젝트는 rest api를 위한 서버이며, 이런 경우 session 기반 인증과는 다르게 statless하게 동작하기 때문이다
이때 rest api에서는 client가 권한이 필요한 요청을 위해 인증정보(OAuth2, jwt...)를 포함시켜야한다
출처

formLogin

이제 로그인창을 지정해보자

http.csrf().disable()
	.formLogin();
return http.build();

위처럼 /login으로 접근하여 spring security 내장 login 페이지로 이동이 가능하다

http.csrf().disable()
	.formLogin(form->form
    	.loginPage("/login") // 로그인 페이지, default: /login
		.defaultSuccessUrl("/") // 로그인 성공 후 이동페이지
		.failureUrl("/login") // 로그인 실패 후 이동페이지
		.usernameParameter("userId") // 아이디 파라미터, default : username
		.passwordParameter("passwd") // 패스워드 파라미터, default : password
		.loginProcessingUrl("/login_proc") // loginfrom action, default: /login
		.successHandler(null) // 로그인 성공 후 핸들러
		.failureHandler(null) // 로그인 실패 후 핸들러
    );
return http.build();

logout

로그아웃 관련 핸들러는 이렇게 지정 가능하다

http.csrf().disable()
	.formLogin(...)
    .logout(logout->logout
        .logoutUrl("/logout") // 로그아웃 url(post)
        .logoutSuccessUrl("/login") //  로그아웃 성공 후 url
        .deleteCookies("JSESSIONID","remember-me") // 로그아웃 후 쿠키 삭제
        .addLogoutHandler(null) // 로그아웃 핸들러
        .logoutSuccessHandler(null) // 로그아웃 성공 후 핸들러
    );

Handler

이제 핸들러를 지정해보자

public class MyLoginSuccessHandler implements AuthenticationSuccessHandler{

    @Override
    public void onAuthenticationSuccess
    	(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        HttpSession session = request.getSession();
        System.out.println("logining");

        session.setAttribute("greeting", authentication.getName() + ", Hello");

        response.sendRedirect("/");
    }
}
...
http.csrf().disable()
	.formLogin(form->form
		.successHandler(new MyLoginSuccessHandler )
    );
return http.build();
...

위처럼 간략하게 핸들러를 지정, 로그인시 할 행동을 지정 할 수 있다

AuthenticationSuccessHandler
AuthenticationFailureHandler
LogoutHandler
...

0개의 댓글