Skip to content

Instantly share code, notes, and snippets.

@ugurcemozturk
Created December 6, 2017 19:12
Show Gist options
  • Save ugurcemozturk/c760071bd134ed5401344f91635b2221 to your computer and use it in GitHub Desktop.
Save ugurcemozturk/c760071bd134ed5401344f91635b2221 to your computer and use it in GitHub Desktop.
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req,
HttpServletResponse res) throws AuthenticationException {
try {
Developer creds = new ObjectMapper()
.readValue(req.getInputStream(), Developer.class);
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword(),
new ArrayList<>())
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain,
Authentication auth) throws IOException, ServletException {
String token = Jwts.builder()
.setSubject(((User) auth.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
.compact();
res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment