title: Role Based Authentication on Restful endpoints in java
body: <p>I'm trying to implement some sort of Role Based authentication. I'm using JWT tokens. I've been looking at guides but all of them mention the use of "Spring boot". How would I setup Role Based authentication on my restful endpoint in Java? Preferably through some sort of filter.</p>
  
  <p>I'm looking for a way to simply add: <code>@Role(Role.ADMIN)</code> before an endpoint.</p>
  
  <p>I've got the following classes already setup:</p>
  
  <ul>
  <li><p>Enum Role:</p>
  
  <pre><code>public enum Role {
      User,
      Admin
  }
  </code></pre></li>
  <li><p>Simple JWT token:</p>
  
  <pre><code>{
   "sub": "users/TzMUocMF4p",
   "exp": 1554646441,
   "username": "username@gmail.com",
   "ID": 6,
   "Role": "Admin",
   "iat": 1554641041
  }
  </code></pre></li>
  <li><p>Simple CRUD endpoint</p>
  
  <pre><code>@Path("User")
  public class UserResource {
  
     @EJB
     private UserDAO userappDAO;
  
  
     @GET
     @JWTTokenNeeded
     @Produces("application/json")
     public List&lt;Userapp&gt; all() {
         return userappDAO.getAll();
     }
  }
  </code></pre></li>
  <li><p>JWT validating (<code>@JWTTokenNeeded</code>) class below:</p>
  
  <pre><code>@javax.ws.rs.NameBinding
  @Retention(RUNTIME)
  @Target({TYPE, METHOD})
  public @interface JWTTokenNeeded {
  }
  </code></pre>
  
  <p>The actual filter:</p>
  
  <pre><code>@Provider
  @JWTTokenNeeded
  @Priority(Priorities.AUTHENTICATION)
  public class JWTTokenNeededFilter implements ContainerRequestFilter {
  
  
      @Override
      public void filter(ContainerRequestContext requestContext) throws IOException {
  
  // Get the HTTP Authorization header from the request
  String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
  
  try {
      // Extract the token from the HTTP Authorization header
      String token = authorizationHeader.substring("Bearer".length()).trim();
      // Validate the token
      Jwts.parser().setSigningKey("MYSECRET".getBytes("UTF-8")).parseClaimsJws(token);
  
  }
  catch (Exception e) {
      requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
  }
  }
  }
  </code></pre></li>
  </ul>
  
  <p>If the user isn't authorized I'd like to exit with:
  <code>requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());</code></p>
  
  <p>If the user IS authorized the endpoint has to do it's thing.</p>