상세 컨텐츠

본문 제목

[WithParents] SpringSecurityConfig 작성 | JWT Token 생성 메서드 작성

Project/WithParents

by yooputer 2023. 1. 16. 14:52

본문

SpringSecurity를 사용하면 기본적으로 모든 페이지에서 로그인을 해야한다

페이지마다 접근권한을 다르게 하기 위해 SpringSecurityConfig를 작성한다


SpringSecurityConfig 작성

config라는 패키지를 새로 생성하고 config패키지 아래에 SpringSecurityConfig라는 클래스를 생성한다

 

WebSecurityConfigurerAdapter을 상속하고 http관련 설정과 web 관련 설정을 해준다

(참고로 WebSecurityConfigurerAdapter는 스프링부트 3.0.1버전에서 사용할 수 없어서 버전을 2.7.5로 내렸다....)

 

다음과 같이 설정하면 "/" 경로와 "/api/auth/testLogin" 경로는 로그인이 없어도 접근할 수 있다

@EnableWebSecurity
@RequiredArgsConstructor
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 필터 비활성화
        http.httpBasic().disable();
        http.csrf().disable();

        // 비연결상태 설정
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 접근권한 설정
        http
            .authorizeRequests()
            .antMatchers(
                "/", "/api/auth/testLogin")
            .permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/**")
            .hasRole("USER");
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }

}

PropertyConfig 작성

JWT Util을 생성하기에 앞서 application.properties에 작성된 JWT key를 사용할 수 있도록하는 PropertyConfig를 작성해보도록 하겠다

 

config 패키지 아래에 PropertyConfig 클래스를 생성한다

 

jwt token을 해독하는 Jwt key를 application.properties에 작성한다

 

다음과 같이 PropertyConfig를 작성한다

앞으로 jwtkey가 필요하면 PropertyConfig를 통해 얻을 수 있다

@Configuration
public class PropertyConfig {

    @Value("${jwtkey}")
    private String jwtkey;
    
    public String getJwtkey() {
        return jwtkey;
    }
}

jwt를 위한 의존성 추가

build.gradle에서 jwt관련 의존성을 추가한다


Jwt Token 생성 메서드 구현

util이라는 패키지를 새로 생성하고 util 패키지 아래에 JwtUtil 클래스를 생성한다

 

JwtUtil 클래스에 다음과 같이 Jwt Token을 생성하는 메서드를 구현한다

@Component
@RequiredArgsConstructor
public class JwtUtil {

    private final PropertyConfig propertyConfig;

    public String createJwtToken(String userId) {

        Map<String, Object> jwtHeader = new HashMap<>();
        jwtHeader.put("typ", "JWT");
        jwtHeader.put("alg", "HS256");

        Map<String, Object> jwtPayload = new HashMap<>();
        jwtPayload.put("user_id", userId);

        Long expiredTime = 1000 * 60L * 60L * 24L * 7L; // 7일
        Date date = new Date();
        date.setTime(date.getTime() + expiredTime);

        Key key = Keys.hmacShaKeyFor(propertyConfig.getJwtkey().getBytes(StandardCharsets.UTF_8));

        return Jwts.builder()
                .setHeader(jwtHeader)
                .setClaims(jwtPayload)
                .setExpiration(date)
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();

    }

}

 

 

관련글 더보기