Created
May 1, 2018 20:29
-
-
Save lusabo/73524262ab3778eb7cbcd0f9ab073556 to your computer and use it in GitHub Desktop.
JwtAuthenticationTokenFilter
This file contains hidden or 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
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