Recently I’m working on my personal project which expose RESTful API for client communication. In order to restrict some access to authenticated user only, It will then require client to login and issue a token upon login (also referring to Authentication token in this post), then client will use the token to identify them self for subsequent request.
Since I’m using Spring MVC framework for the implementation, @RequestHeader annotation come in handy. Just grab the header, set as parameter then call the business implementation for further processing. Sounds pretty easy ya 🙂
But when more and more method require this token, this become tedious where you keep adding @RequestHeader into your controller method just to get the token. So I decided to make use of filter for this.
After reading online documentation and article, I have created the scaffolding code @ github, which will do the following:
1. Get the “Authentication” header from each request.
2. Parse the header to get the token and query user based on the token.
3. Set the authenticated user object into SecurityContextHolder, and get back same user object anywhere within the request thread execution time. (By default the SecurityContextHolder uses a ThreadLocal to store details)
4. Each request will then check for role validity to access the business method.
Feel free to check out the code for study and fork it for your own usage, yet most important…………… have fun 🙂