Last active
June 7, 2020 20:13
-
-
Save sophea/b844d0be261701a496b79420e208cce5 to your computer and use it in GitHub Desktop.
Jwt Request Filter
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
package com.sma.security.config; | |
@Component | |
public class JwtRequestFilter extends OncePerRequestFilter { | |
public static final String AUTHORIZATION = "Authorization"; | |
public static final String BEARER = "Bearer "; | |
@Autowired | |
private JwtTokenService jwtTokenService; | |
@Override | |
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { | |
final Optional<String> jwt = getJwtFromRequest(request); | |
jwt.ifPresent(token -> { | |
try { | |
if (jwtTokenService.validateToken(token)) { | |
setSecurityContext(new WebAuthenticationDetailsSource().buildDetails(request), token); | |
} | |
} catch (IllegalArgumentException | MalformedJwtException | ExpiredJwtException e) { | |
logger.error("Unable to get JWT Token or JWT Token has expired"); | |
//UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("anonymous", "anonymous", null); | |
//SecurityContextHolder.getContext().setAuthentication(authentication); | |
} | |
}); | |
filterChain.doFilter(request, response); | |
} | |
private void setSecurityContext(WebAuthenticationDetails authDetails, String token) { | |
final String username = jwtTokenService.getUsernameFromToken(token); | |
final List<String> roles = jwtTokenService.getRoles(token); | |
final UserDetails userDetails = new User(username, "", roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())); | |
final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, | |
userDetails.getAuthorities()); | |
authentication.setDetails(authDetails); | |
// After setting the Authentication in the context, we specify | |
// that the current user is authenticated. So it passes the | |
// Spring Security Configurations successfully. | |
SecurityContextHolder.getContext().setAuthentication(authentication); | |
} | |
private static Optional<String> getJwtFromRequest(HttpServletRequest request) { | |
String bearerToken = request.getHeader(AUTHORIZATION); | |
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER)) { | |
return Optional.of(bearerToken.substring(7)); | |
} | |
return Optional.empty(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment