title: jax-rs rest webservice authentication and authorization
body: <p>I have a web application that needs to allow users using different webclients (browser, native mobile app, etc) to register. After signing in they can access restricted content or their own content (like entries they create, etc).</p>
  
  <p>What I did so far: I created a jax-rs rest webservice (I'm hosting my application on glassfish) that exposes the following methods:</p>
  
  <ul>
  <li>register - user POST's his desired username/password/email/etc; if username/email is unique, an entry for this user is created in the database (I'm using Hibernate for persistence)</li>
  <li>login - user POST's username and password. If they are ok a UUID is created and returned to the user (this will be used as a token for future requests). I have a table called logedusers, with userID, token, validSince as columns.</li>
  </ul>
  
  <p>Here is where it gets confusing for me.</p>
  
  <p>Let's say that I have another method, getUserEntries, that should return all the entries made by the user. To make this clearer, there will be a Entry table with the following fields: entryId, userId, text.</p>
  
  <p>What is the best approach here? </p>
  
  <p>What i do now, is I make a get request and pass in the token like this: </p>
  
  <p><code>localhost:8080/myApp/getUserEntries?token=erf34c34</code> </p>
  
  <p>Afterwards, if the token is valid, I get the userID from the logedusers table and based on that userId, get all the entries and return them as json.</p>
  
  <p>Something like this:</p>
  
  <pre class="lang-java prettyprint-override"><code>@GET
  @Path("getUserEntries")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getUserEntries(@QueryParam("token") String token) {      
      String userId=getUserIdFromToken(token);
      if (userId == null){
          return Response.status(Response.Status.UNAUTHORIZED).build();
      } else {
          //get some data associated with that userId, put it in the response object and send it back
          return Response.ok().entity(response).build();
      }
  }
  </code></pre>
  
  <p>However, what happens if I have more methods that provide data if they are called by a valid user?</p>
  
  <p>I'd have to do this check at the beginning of every method.</p>
  
  <p>I want to make this authorization process transparent </p>
  
  <p>So, two major questions here:</p>
  
  <ol>
  <li>Is this design ok? The whole authenticate with user/pass, server creates and stores and sends token to the user, user sends token on future requests.</li>
  <li>What do I do if i have many endpoints that need to determine the identity of the calling user? Can I mark them with some annotations, use some sort of security provider / authenticator (where I can add my own logic for validating - eg check to see if the token isn't older than 5 days, etc). </li>
  </ol>
  
  <p>Thanks</p>