Skip to content

Instantly share code, notes, and snippets.

@yigiterinc
Last active August 30, 2023 13:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yigiterinc/74e24d263cc403a9057cf046d514860a to your computer and use it in GitHub Desktop.
Save yigiterinc/74e24d263cc403a9057cf046d514860a to your computer and use it in GitHub Desktop.
JWT authentication filter class for my tutorial in Medium
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();
}
}
@teja463
Copy link

teja463 commented Aug 14, 2020

closing bracket missing on line no 8

@yigiterinc
Copy link
Author

closing bracket missing on line no 8

Fixed, thank you 👍

@waqas-idrees-confiz
Copy link

From which package did you add JWT.Create

@yigiterinc
Copy link
Author

From which package did you add JWT.Create

Auth0 JWT

@teja463
Copy link

teja463 commented Dec 3, 2020

implement the org.springframework.security.core.userdetails.UserDetails interface

@arvind-pal
Copy link

Is it the same implementation from Auth0 example ?
https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/

@talitaedwiges
Copy link

how do I recognize the EXPIRATION_TIME of the SecurityConstants class?

@MateusRosario
Copy link

missing super(authenticationManager); on line 6;

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