Last active
August 30, 2023 13:48
-
-
Save yigiterinc/74e24d263cc403a9057cf046d514860a to your computer and use it in GitHub Desktop.
JWT authentication filter class for my tutorial in Medium
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; | |
setFilterProcessesUrl("/api/services/controller/user/login"); | |
} | |
@Override | |
public Authentication attemptAuthentication(HttpServletRequest req, | |
HttpServletResponse res) throws AuthenticationException { | |
try { | |
User creds = new ObjectMapper() | |
.readValue(req.getInputStream(), User.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 { | |
String token = JWT.create() | |
.withSubject(((User) auth.getPrincipal()).getUsername()) | |
.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) | |
.sign(Algorithm.HMAC512(SECRET.getBytes())); | |
String body = ((User) auth.getPrincipal()).getUsername() + " " + token; | |
res.getWriter().write(body); | |
res.getWriter().flush(); | |
} | |
} |
Is it the same implementation from Auth0 example ?
https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/
how do I recognize the EXPIRATION_TIME of the SecurityConstants class?
missing super(authenticationManager);
on line 6;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
implement the
org.springframework.security.core.userdetails.UserDetails
interface