Skip to content

Instantly share code, notes, and snippets.

@learnit-codeit
Created April 8, 2021 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save learnit-codeit/b6558afdb44159de54faf9e0d3d962ed to your computer and use it in GitHub Desktop.
Save learnit-codeit/b6558afdb44159de54faf9e0d3d962ed to your computer and use it in GitHub Desktop.
@Component
public class JwtFilter extends OncePerRequestFilter {
@Autowired
private UserRepository userRepository;
@Autowired
private JWTUtils jwtUtils;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String authorizationHeader = httpServletRequest.getHeader("Authorization");
String token = null;
String userName = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
token = authorizationHeader.substring(7);
userName = jwtUtils.extractUsername(token);
}
if (userName != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userRepository.findUserByUsername(userName)
.orElseThrow(() -> new UsernameNotFoundException("User not present"));;
if (jwtUtils.validateToken(token, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
@clement-bey
Copy link

clement-bey commented Mar 9, 2022

Hi !

I found a reference to this class on https://medium.com/javarevisited/spring-security-jwt-authentication-in-detail-bb98b5055b50

I just wanted to give you some advices / correction suggestions :

  1. Your component is a filter that trigger at every request. The fact that it is in charge of using UserRepository bean will lead to a problem --> even with a valid token, a DB request ( or rest call to your authentication server depending ) will be made.

You should consider to include Spring authorities in your JWT token as a claim. Doing it will allow you to remove UserRepo from your filter, avoid those overkill DB request ( or network communication ).
You'll be able to construct your Authentication only with the token and rely on the signature to certify data.

Leaving this point aside, your article is very good. Thank you for this good read :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment