WebSecurityConfig
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.headers().frameOptions().disable();
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/user/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutUrl("/user/logout")
.permitAll()
.and()
.exceptionHandling()
.and()
.addFilterBefore(new JwtAuthenticationFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class);
마지막 addFilterBefore을 통해 들어오는 요청을 검증한다.
필터링 함수 내용은 다음과 같다.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String token = jwtProvider.resolveToken((HttpServletRequest) request);
try {
if (token != null && jwtProvider.validateJwtToken(request, token)) {
// 토큰이 유효하면 토큰으로부터 유저 정보를 받아온다.
Authentication authentication = jwtProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception e) {
e.printStackTrace();
}
chain.doFilter(request, response);
}
resolveToken함수에서 들어온 토큰 스트링을 반환해주고 이를 바탕으로 토큰이 유효한지 판단해 요청을 처리한다.
resolveToken함수 내용은 다음과같다.
public String resolveToken(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
String token = null;
if(cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("mytoken")) {
token = cookie.getValue();
}
}
}
return token;
}
토큰은 쿠키에 저장되어있기때문에 쿠키에서 mytoken의 value를 가져와 반환한다.
홍서님 보구파요~~ 얼렁 돌아와