Project NewWebApp, requirements:

Architect : ‚We have to implement REST Services, everything should be stateless and the client is a JS Framework. All the last techs, isn’t it cool? And avoid cookies, they are not safe, they have a bad reputation and there are too many policies against them.‘

Business analyst: ‚There is a welcome page, the user has to login to access the local secured resources. I suggest to avoid cookies too, they are bad for the health and they can ruin our marketing campaign.’

You : ‚ No session?! Rest services?! No cookies?! How I verify the identity of the user? I have to request his identity at every request?‘

OAuth 2 can be a solution to your problem

The client has to login with the Authorization Server, this can be connected to your LDAP in the company or with an external service like Google or Amazon. This server generate a Token that is stored by the javascript client. This token has to be sent in every request from the client to your Java application. Your application ask to the server if the token is valid, in case it is affirmative the user has the authorization.

Here described the communication:

 

Where to store the token?

The cookies are not safe and they can give a lot of troubles. One solution is to store the token in the session storage of the browser. In this case when the user will close the browser the session will be closed.


saveMyToken(accessTokenYouReceivedFromTheServer) {
    yourService.$window.sessionStorage.setItem('myToken', accessTokenYouReceivedFromTheServer)
}

When you need it you can retrieve the token easily:


getMyStoredToken() {
yourService.$window.sessionStorage.getItem('myToken');
}

How to prepare a request with the token received from the server:

sendRequestToTheBackend() {
    return this.$http(method:'GET', url:'http://yourBackend/restResourceURL',
    headers: this.getHeaders()
})}

getHeaders() {
return {
'Authorization': 'Bearer ' + this.getMyStoredToken,
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}

What is this ‘Bearer’ thing? Here your answer

How to implement the complete solution? Soon I will update the Angular / Spring Boot tutorial with a simple implementation.