Created
December 6, 2017 19:12
-
-
Save ugurcemozturk/c760071bd134ed5401344f91635b2221 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 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