Created
March 2, 2018 15:41
-
-
Save dvas0004/61628cd55074e1c718f6ea36cf09a3aa 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
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