Created
April 8, 2021 04:09
-
-
Save learnit-codeit/b6558afdb44159de54faf9e0d3d962ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :
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 :)