Skip to content

Instantly share code, notes, and snippets.

@yigiterinc
Created August 9, 2020 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yigiterinc/353558bb33a0d4bfb37c054bf3ef2abf to your computer and use it in GitHub Desktop.
Save yigiterinc/353558bb33a0d4bfb37c054bf3ef2abf to your computer and use it in GitHub Desktop.
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
public JWTAuthorizationFilter(AuthenticationManager authManager) {
super(authManager);
}
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
String header = req.getHeader(HEADER_STRING);
if (header == null || !header.startsWith(TOKEN_PREFIX)) {
chain.doFilter(req, res);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}
// Reads the JWT from the Authorization header, and then uses JWT to validate the token
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// parse the token.
String user = JWT.require(Algorithm.HMAC512(SECRET.getBytes()))
.build()
.verify(token.replace(TOKEN_PREFIX, ""))
.getSubject();
if (user != null) {
// new arraylist means authorities
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
@nscheers
Copy link

nscheers commented Nov 5, 2020

Missing closing bracket on last line

@yigiterinc
Copy link
Author

Missing closing bracket on last line

Yep, copy paste issues 👍

@satbbus
Copy link

satbbus commented Feb 12, 2022

Where is the JWT imported from ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment