Skip to content

Instantly share code, notes, and snippets.

@lusabo
Created May 1, 2018 20:29
Show Gist options
  • Save lusabo/73524262ab3778eb7cbcd0f9ab073556 to your computer and use it in GitHub Desktop.
Save lusabo/73524262ab3778eb7cbcd0f9ab073556 to your computer and use it in GitHub Desktop.
JwtAuthenticationTokenFilter
package com.eco.security;
// Imports
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
private static final String AUTH_HEADER = "Authorization";
private static final String BEARER_PREFIX = "Bearer ";
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenUtils jwtTokenUtils;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String token = request.getHeader(AUTH_HEADER);
if (token != null && token.startsWith(BEARER_PREFIX)) {
token = token.substring(7);
}
String username = jwtTokenUtils.getUsernameFromToken(token);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtTokenUtils.isTokenValid(token)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment