Java REST service using authentication token

12,410

Solution 1

Heres my input:

  • I would save the token in DB, in case you need to restart the server you don't want to lose all your user's tokens. You could potentially save it in memory as well to speed up requests and only look it up in DB if it is not found in memory.

  • I would accept the token in the header. I would put the rest service on HTTPS so the request is encrypted and then you don't need to worry about encrypting the token manually in the request

  • I would probably look at JAX-RS and see what features it offers

Solution 2

I recently blogged on how to set up Role-based authorization in a JAX-RS REST API using both a simple session token approach and a more secure method of signing requests using the session token as a shared secret.

It boils down to:

  • Get a session token from the server along with some identifier for the user
  • Use the token to encrypt the information in the request
  • Also use a timestamp and nonce value to prevent MITM attacks
  • Never pass the session token back and forth except for when retrieving it initially
  • Have an expiry policy on session tokens

Solution 3

Saving the token in a bean or hash table would not be persistent. A DB would persist between executions.

If you are going to be using REST then you can either pass the authentication in the parameters to the method, or in the request header itself. Encryption is a different matter. I guess it depends on the scale of the system, and how open it is. If security is a top importance, then yes, you should find some form of encryption.

I have done similar things using the Spring Framework, and Spring Security. These things are relatively simple using this. To write custom code is to reinvent the wheel. There are many frameworks out there which will help you. However, you would then have the learning curve of the framework.

Share:
12,410
Spring
Author by

Spring

Updated on June 14, 2022

Comments

  • Spring
    Spring almost 2 years

    On my web app using Java EE 6. I want to expose some of my functionality as a Json Rest Service. I want to use authentication tokens for login, User will send their username, password and server will send back a token, which will be used to authorize the user on their further requests for a given time..

    A few questions bothering me so far;

    • When the server creates the token and sends to client, should server save it in a DB OR in a Bean using something like a hashtable as userid-token pairs?

    • Can I get some help using any Java EE specific API or this has to be all custom code?

  • Spring
    Spring over 11 years
    could you also look at this one? I created another question, stackoverflow.com/questions/13997040/…