Spring Security

[Security] 스프링 시큐리티 설정 및 사용자 정의 보안기능 구현

cornarong 2021. 10. 3. 18:49

의존성 추가 (gradle)

implementation 'org.springframework.boot:spring-boot-starter-security'

스프링 시큐리티 의존성을 추가 후 서버를 기동하면 기본적으로 시큐리티의 초기화 작업 및 보안설정이 이루어진다.

별도의 설정이나 구현을 하지 않아도 기본적인 웹 보안 기능이 현재 시스템에 연동이 되어 작동한다.

 

WebSecurityConfigurerAdapter 클래스는 기본적인 웹보안 기능의 활성화 및 설정등.. 모든 처리를 한다.

HttpSecurit 클래스는 세부적인 기능을 설정할 수 있는 인증API, 인가API를 제공한다.

 

사용자 임의 설정이 없을 경우 기본으로 아래의 api들을 호출하여 설정을 초기화 한다. (Default)

	private void applyDefaultConfiguration(HttpSecurity http) throws Exception {
		http.csrf();
		http.addFilter(new WebAsyncManagerIntegrationFilter());
		http.exceptionHandling();
		http.headers();
		http.sessionManagement();
		http.securityContext();
		http.requestCache();
		http.anonymous();
		http.servletApi();
		http.apply(new DefaultLoginPageConfigurer<>());
		http.logout();
	}

스프링 시큐리티에서 제공되는 기본 로그인 화면이다.

추가로 계정 한개를 제공해준다.

Username : user

Password : 랜덤 문자열 (서버 기동시 아래 사진과 같이 콘솔에 출력된다.)

 

기본 계정을 application.properties에 설정 해줌으로 사용자 임의로 설정이 가능하다.


아래와 같이 사용자 정의 보안 설정 클래스를 하나 만들고 몇가지 인가, 인증 기능으로 보안을 설정해보자.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 인가 정책
        http
                .authorizeRequests() // 요청에 의한 보안을 실행한다.
                .anyRequest().authenticated(); // 모든요청을.인증한다.
        // 인증 정책
        http
                .formLogin() // formLogin 방식과 httpBasic 방식이 있다. (formLogin 방식 사용)
                .loginPage("/loginPage") // 로그인 페이지 url (기본으로 제공되는 로그인 화면 페이지도 있다.)
                .defaultSuccessUrl("/") // 로그인 성공시 url (우선순위 마지막)
                .failureUrl("/loginPage") // 로그인 실패시 url (우선순위 마지막)
                .usernameParameter("userId") // id 파라미터 명
                .passwordParameter("passwd") // password 파라미터 명
                .loginProcessingUrl("/login_proc") // form의 action 경로url
                .successHandler(new AuthenticationSuccessHandler() { // 기본적으로 성공시 success 핸들러를 호출한다. 이처럼 생성하여 직접 구현 가능하다.
                    // 로그인 성공시 authentication 정보를 매개변수로 받아서 ~
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        System.out.println("authentication : " + authentication.getName());
                        response.sendRedirect("/");
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() { // 기본적으로 실패시 fail 핸들러를 호출한다. 이처럼 생성하여 직접 구현 가능하다.
                    // 로그인 실패시 exception 정보를 매개변수로 받아서 ~
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                        System.out.println("exception : " + exception.getMessage());
                        response.sendRedirect("/loginPage");
                    }
                })
                .permitAll(); // login 화면은 인증없이 누구나 접근이 가능해야 한다.

    }
}

추가로 defaultSuccessUrl 또는 failureUrl보다 successHandlerfailureHandler가 우선순위를 갖는다.

즉, redirect url은 우선순위가 빠른 api의 url로 가게된다.