본문 바로가기
Spring Boot/Spring Security

[Spring security + Jwt #1] Spring Security 설정하기

by Lee David 2022. 2. 21.
반응형
1. dependency 설정
<!-- Spring Security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!--jwt Token Library-->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

jwt 토큰이 session 처럼 기본 설정으로 적용된 것이 아니기 때문에 dependency를 따로 추가 해줘야 합니다.

2. Spring Security 설정 class 생성
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	...
}

@Configuration - 빈 등록

@EnableWebSecurity - Security class를 등록합니다.

@AllArgsConstructor - 서비스 빈을 불러와서 사용하기 위해 명시 합니다.

2-1. PasswordEncoder 등록
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

유저가 패스워드를 db에 저장/매칭 등을 할때 사용하는 Spring Security 내부 메서드를 빈으로 등록해줍니다.

패스워드를 평문으로 저장하는 것을 보안상 지양하기 위해 사용됩니다.

2-2. static 파일 경로 추가하기
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/css/**", "/js/**", "/images/**", "/lib/**");
}

만약 css, javascript, image나 외부 라이브러리 등의 경로를 사용할때 등록해 주시면 됩니다.

thymeleaf 등의 template engine을 사용할때는 꼭 등록해주셔야 resource 하위 등록된 경로의 파일들을 사용 가능합니다.

2-3. Jwt 토큰 필터 등록
// Jwt 토큰을 필터링 할 class를 생성하고 등록해 줍니다.
private JwtAuthenticationFilter jwtAuthenticationFilter;

* Jwt 토큰 필터 클래스는 다음 포스팅에서 이어 작성하겠습니다.

2-4. Request 정보 등록
@Override
    protected void configure(HttpSecurity http) throws Exception {
        // jwt 토큰을 사용할때에는 사용하지 않는 설정 값입니다.
        // 비슷한 성격의 토큰을 또 설정할 필요는 없습니다.
        http.csrf().disable();
        // CORS 설정
        // Cross Origin Resource Sharing CORS를 통한 보안 이슈가 발생함으로
        // 같은 ip 대역의 서비스끼리 통신할때에는 어떤 포트를 허용할지 지정합니다.
        http.cors().configurationSource(request -> {
            var cors = new CorsConfiguration();
            cors.setAllowedOrigins(List.of("http://localhost:3000"));
            cors.setAllowedMethods(List.of("GET","POST", "PUT", "DELETE", "OPTIONS"));
            cors.setAllowedHeaders(List.of("*"));
            return cors;
        });
        http.authorizeRequests()
                // 페이지 권한 설정
                    .antMatchers("/api/admin/**").hasRole(Role.ADMIN.getValue())
                    .antMatchers("/api/user/**").hasAnyRole(Role.ADMIN.getValue(), Role.MEMBER.getValue())
                    .antMatchers("/api/common/**").permitAll()
                    .antMatchers("/**", "/fragments/**", "/sign/**", "/error/**", "/img/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                	// jwt 토큰을 사용하게 되면 세션을 사용하지 않는다고 서버에 명시적으로 선언해 주어야 합니다.
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 403 예외처리 핸들링 - 토큰에 대한 권한과 요청 권한이 달라짐
                    .exceptionHandling()
                    .accessDeniedHandler(new CustomAccessDeniedHandler())
                .and()
                // 토큰이 없거나 위 변조된 경우
                    .exceptionHandling()
                    .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
                .and()
                // 토큰 유효성 필터링에 필요한 클래스를 등록 합니다.
                // jwtAuthenticatioinFilter 생성은 다음 포스팅에서 다루겠습니다.
                    .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

그럼 Spring Security에 필수로 등록해야할 내용들이 정리 되었습니다.

 

반응형