[내배캠/TIL(7/4)]cookie에서 꺼내서 토큰 인증하기

손홍서·2022년 7월 5일
1

Spring

목록 보기
17/24

day50 TIL

cookie에서 꺼내서 토큰 검증하기

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를 가져와 반환한다.

profile
Hello World!!

1개의 댓글

comment-user-thumbnail
2022년 7월 6일

홍서님 보구파요~~ 얼렁 돌아와

답글 달기