Skip to content

Instantly share code, notes, and snippets.

@dvas0004
Created March 2, 2018 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvas0004/61628cd55074e1c718f6ea36cf09a3aa to your computer and use it in GitHub Desktop.
Save dvas0004/61628cd55074e1c718f6ea36cf09a3aa to your computer and use it in GitHub Desktop.
public class JWTFilter implements Filter{
private String jwtSecret;
public JWTFilter(String jwtSecret){
this.jwtSecret = jwtSecret;
}
@Override
public void destroy() {
// Do nothing
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
String jwtSecret = this.jwtSecret;
System.out.println("Checking JWT...");
String token = null;
Boolean verified = false;
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response =(HttpServletResponse) res;
token = request.getHeader("authorization");
try {
Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("YOUR ORGANIZATION HERE")
.build();
DecodedJWT jwt = verifier.verify(token);
verified = jwt.getClaim("API_ALLOWED").asBoolean();
Map<String, Claim> roles = jwt.getClaims();
String subject = jwt.getSubject();
ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
for (String role: roles.keySet()){
authorities.add(new SimpleGrantedAuthority(role));
}
UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken( subject,
"",
authorities);
SecurityContextHolder.getContext().setAuthentication(newAuth);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JWTVerificationException exception){
//Invalid signature/claims
System.out.println("Invalid JWT verification");
exception.printStackTrace();
}
if (verified) {
chain.doFilter(req, res);
} else {
res.reset();
System.out.println("Could not verify JWT...");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment