Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. @Secured
  2. @Provider
  3. @Priority(Priorities.AUTHENTICATION)
  4. public class AuthenticationFilter implements ContainerRequestFilter {
  5. private static Logger LOGGER = LoggerFactory.getLogger(AuthenticationFilter.class);
  6. @Override
  7. public void filter(ContainerRequestContext requestContext) throws IOException {
  8. LOGGER.info("[AuthenticationFilter] started");
  9. // Get the HTTP Authorization header from the request
  10. String authorizationHeader =
  11. requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
  12.  
  13. // Check if the HTTP Authorization header is present and formatted correctly
  14. if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
  15. throw new NotAuthorizedException("Authorization header must be provided");
  16. }
  17.  
  18. // Extract the token from the HTTP Authorization header
  19. String token = authorizationHeader.substring("Bearer".length()).trim();
  20.  
  21. try {
  22. // Validate the token
  23. validateToken(token);
  24. } catch (Exception e) {
  25. requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
  26. }
  27. LOGGER.info("[AuthenticationFilter] ended");
  28. }
  29.  
  30. //TODO: add the key in properties
  31. //TODO: check the username in DB
  32. private void validateToken(String token) throws Exception {
  33. // Check if it was issued by the server and if it's not expired
  34. // Throw an Exception if the token is invalid
  35. String username = Jwts.parser()
  36. .setSigningKey("jeSuisLaSecretPhrase,1234,ilFaudraMePlacerEnConf,Merci")
  37. .parseClaimsJws(token)
  38. .getBody()
  39. .getIssuer();
  40. if(!"admin".equals(username)){
  41. throw new NotAuthorizedException("bad token");
  42. }
  43.  
  44. }
  45. }
  46.  
  47. ...
  48. <jaxrs:providers>
  49. <ref bean="authorizationFilter" />
  50. </jaxrs:providers>
  51. ...
  52. <bean id="authorizationFilter" class="com....AuthenticationFilter">
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement