이 게시글은 유튜브 개발자 유미님의 무료강의 스프링 시큐리티 JWT 12, 13 : 사용자 정보, CORS 을 수강하며 공부한 내용을 담고있습니다.
이 게시글은 공부한 내용을 제가 보기 편하게 정리한 내용이므로 정확한 정보는 위 영상을 시청해주세요.
이 게시글은 기본적인 Spring 기본 실습을 해봤다는 가정하에 기초적인 설명은 생략되어 있습니다.
또한 실습을 따라가며 기본적인 JWT 사용방법을 학습하기에 상세한 원리와 설명은 없는 경우가 있습니다.
사용자 정보 가져오기
JWT Filter 에서 SecurityContextHolder 에 사용자 정보를 보관했다.
username 등과 같이 사용자 정보가 필요한 경우 SecurityContextHolder 에서 꺼내 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Controller
@ResponseBody
public class MainController {
@GetMapping("/")
public String mainP() {
// main page
// JWT Filter 에서 SecurityContextHolder 에 사용자 정보를 보관했다.
// SecurityContextHolder 에서 사용자 정보를 가져와본다.
String username = SecurityContextHolder.getContext().getAuthentication().getName();
String role;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
Iterator<? extends GrantedAuthority> iter = authorities.iterator();
GrantedAuthority auth = iter.next();
role = auth.getAuthority();
return "Main Controller" + ", username : " + username + ", role : " + role;
}
}
1
2
3
4
5
6
// JWT Filter 의 일부분을 다시 보자.
CustomUserDetails customUserDetails = new CustomUserDetails(userEntity);
Authentication authToken = new UsernamePasswordAuthenticationToken(customUserDetails, null, customUserDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authToken);
JWT Filter 를 보면 SecurityContextHolder.getContext() 에 setAuthentication(authToken) 를 수행하여 사용자 정보를 보관했다.
반대로 꺼내려면 getAuthentication() 를 수행하면 된다.
나머지 코드도 마찬가지다. 분해는 조립의 역순이라고 생각하면 된다.

MainController 코드를 전부 작성 후 테스트를 한다.
일단 /login 으로 요청을 하여 JWT 를 발급받고, 만료되기 전에 재빠르게 header 에 JWT 를 넣고 / 으로 요청하면 200 응답과 함께 Main Controller, username : 값, role : 값 문자열을 받을 수 있다.
CORS
CORS(Cross Origin Resource Sharing) 은 출처(Origin)이 서로 다른 곳(Cross)에서 Resource 를 가져올 수 있도록 하는 매커니즘을 의미한다.
예를 들어, 네이버에 접속했는데 해당 사이트의 리소스를 구글같은 곳에서 가져오면 브라우저는 악성행위라 판단하여 차단한다.
하지만 항상 동일 호스트에 대해 리소스를 가져올 수는 없는 법이다. 예를 들어 프론트 서버와 백엔드 서버를 분리한다던지 할 수 있기 때문에 일부 출처에 대해서는 허용을 해줘야한다.
CORS 설정
CORS 를 설정하기 위해서는 기본적으로 WebMvcConfig 에서 설정해주면 된다. 하지만 Spring Security 를 사용하므로 SecurityFilterChain 에서도 설정해주어야 한다.
SecurityFilterChain
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Configuration
@EnableWebSecurity
public class SecurityConfig {
// (나머지 생략)
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// (나머지 생략)
// CORS 설정
http.cors((cors)-> {cors.configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration configuration = new CorsConfiguration();
// CORS 를 허용할 호스트와 포트번호를 작성한다.
// 여기서는 프론트의 포트번호가 3000 이라고 가정하고 작성한다.
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
// 허용할 메소드를 설정한다. GET/POST/PUT/DELETE 모두 혀용할 것이다.
configuration.setAllowedMethods(Collections.singletonList("*"));
// 브자우저가 credentials(쿠키, 인증헤더 등) 를 보내는 것을 허용한다.
configuration.setAllowCredentials(true);
// 허용할 헤더를 설정한다. 모든 헤더를 허용한다.
configuration.setAllowedHeaders(Collections.singletonList("*"));
// 유지할 시간 설정한다.
configuration.setMaxAge(3600L);
// server 에서 client 로 응답을 보낼 때 허용할 헤더를 설정한다.
configuration.setExposedHeaders(Collections.singletonList("Authorization"));
return configuration;
}
});});
return http.build();
}
}
SecurityFilterChain 에 http.cors 를 추가해준다.
설명은 주석에 나와있는게 전부다.
WebMvcConfigurer
1
2
3
4
5
6
7
8
9
public class CorsMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 모든 Mapping(GetMapping, PostMapping) 에 대해서 추가한다.
// 출처가 localhost:3000 인 것을 허용.
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000");
}
}
위에선 SpringSecurity 를 사용하면 필요한 CORS 설정이고, 이건 Spring MVC 에서 필요한 CORS 설정이다.
CorsMvcConfig 클래스를 하나 만들고 WebMvcConfigurer 를 implements 한다.
WebMvcConfigurer 의 메서드 중 addCorsMappings 를 오버라이딩해 CORS 를 설정할 수 있다.
코드에 대한 설명은 주석과 같다.
이전 포스팅 : JWT 검증 필터