JWT 적용하기 (2)

jb kim·2022년 3월 12일
0

REST API 블로그 앱

목록 보기
54/65

요청시(필터로 처리)

5. JwtAuthenticationFilter

public class JwtAuthenticationFilter extends OncePerRequestFilter {

	@Autowired
	private JwtTokenProvider tokenProvider;
	
	@Autowired
	private CustomUserDetailsService customUserDetailsService;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		
		// 1. http request에서 토큰을 가져온다 (아래에 메소드 생성)
		String token = getJWTfromRequest(request);
		// 2. 토큰 유효성 검사
		if(StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
			// 3. 토큰에서 username 가져오기
			String username = tokenProvider.getUsernameFromJWT(token);
			// 4. 토큰에서 유저디테일 정보들을 가져오기
			UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
			
			UsernamePasswordAuthenticationToken authenticationToken = 
					new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
			
			authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
			// 5. 시큐리티 설정
			SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		}
		
		filterChain.doFilter(request, response);
	}

	// 리퀘스트에서 Bearer <accessToken> 을 가져옴
	private String getJWTfromRequest(HttpServletRequest request) {
		String bearerToken = request.getHeader("Authorization");
		if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){
			return bearerToken.substring(7, bearerToken.length());
		}		
		return null;
	}	
}

6. JWTAuthResponse DTO (payload)

public class JWTAuthResponse {
	private String accessToken;
	private String tokenType = "Bearer";
	
	public JWTAuthResponse(String accessToken) {
		this.accessToken = accessToken;
	}

	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	public String getTokenType() {
		return tokenType;
	}

	public void setTokenType(String tokenType) {
		this.tokenType = tokenType;
	}
		
}

참고 Filter
https://gardeny.tistory.com/35
참고 OncePerRequestFilter
https://minkukjo.github.io/framework/2020/12/18/Spring-142/
참고 Bearer
https://velog.io/@cada/%ED%86%A0%EA%B7%BC-%EA%B8%B0%EB%B0%98-%EC%9D%B8%EC%A6%9D%EC%97%90%EC%84%9C-bearer%EB%8A%94-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C

profile
픽서

0개의 댓글