Tigran
Tigran

Reputation: 1057

Spring boot REST token authorization and authentication best practices

What is the best practise for authorization and authentication of users in REST spring boot?

I am building web app with standard pages + REST API for mobile. I looked at many articles about Spring security and basically most of them goes with some sort of fitler approach that will allow or block REST calls. In my case, however, I have some auth logic based on who the user is. For example, there is a /update API that updates user information, and user can update himself, but cannot update other person. Initially I thought to use next auth schema:

Is this the right approach to implement? I have a pretty big mess in my head after reading articles about spring boot security. At least: session auth will not work for me (REST is stateless). I want to make auth for mobile device without storing login/password there.

Does it make sense to pass this token in the REST body itself? What in case of GET method?

Many thanks for sharing your knowledge.

Upvotes: 6

Views: 15998

Answers (2)

user3444718
user3444718

Reputation: 1625

Cookie approach seems perfect for the use case. Token can be tied up with user id. Filter can extract cookie and pass user id for example as header to apis - that should take care of GET...

Upvotes: 0

rhinds
rhinds

Reputation: 10043

Did you find a solution to your problem?

I have answered this problem elsewhere, if you are sure you won't want to open up the API to other developers/clients in the future (if you do then you should look at OAuth) then a simple token based solution will work.

Something basically along the lines of this:

  • Setup a standard html login page, that you can use for user login to the app
  • setup spring security to return a cookie on sucessful login with an authentication token
  • in your mobile app, embed a WebView (or equivalent) and load this login form - allow the user to login via that webview, on response grab the cookie and store the token (as mobile is generally single user, you can keep that pretty long to save mobile users having to keep logging in)
  • Add a security filter to the the REST API to authenticate against the token (from the mobile app pass the token in the header for example) - then you will be able to use normal spring authentication context for current users etc.

This approach is suggested by Google here: (EDIT: Google seems to have changed the page I originally read to be about using Google+ sign in and OAuth2.0 - I can't see a link to their general Mobile/API docs so here it is in the web archive :) )

I have also written up my implementation here:

Overview of the approach using Spring security

The code & details

Although this was really just an experiment/Proof of concept, it might be useful in your thinking.

Upvotes: 3

Related Questions