public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
private JwtUtil jwtUtil;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtil) { super(authenticationManager); this.jwtUtil = jwtUtil; }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { Authentication authentication = getAuthentication(request);
if(authentication != null){ SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(authentication); }
chain.doFilter(request, response); }
private Authentication getAuthentication(HttpServletRequest request){ String token = request.getHeader("Authorization"); if(token == null){ return null; }
Claims claims = jwtUtil.getClaims(token.substring("Bearer ".length())); Authentication authentication = new UsernamePasswordAuthenticationToken(claims, null);
return authentication; } }
|