I have configured spring boot for rest controller. I created many api but i need to validate my token information in every api at begging, Is user is authorized or not base on provided token.
During the signin i am generating token that token required in every api for accessing information. if token is not valid then i need to return message Sorry, your provided token information has been expired or not exists.
below is the my api.
@RequestMapping(value="/delete", method= RequestMethod.DELETE)
public Map<String, Object> delete(@RequestBody String reqData,HttpServletRequest request) {
Map<String, Object> m1 = new HashMap<String,Object>();
JSONObject jsonData = new JSONObject(reqData);
Token token= tokenDao.getByTokenCode(jsonData.getString("token"));
if(token==null){
m1.put("status", "error");
m1.put("message", "Sorry, your provided token information expired or not exists.");
return m1;
}
//here my logic to remove user from database.
}
Is there any way to check token functionality in service method or using annotation, so i need to remove that same code in every api and need to use one common functionality.
you can use HandlerInterceptor to handle you token.
HandlerInterceptor.preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) will execute before any RequestMapping.
validate you token in preHandle.if token is valid continue,else throw exception,controller advice will handler the rest.
expose bean class of MappedInterceptor,spring will auto load HandlerInterceptor bean contains.
ControllerAdvice and ExceptionHandler can catch exception and return error message
full example
for controller pass user id and token and check the token. you need to update
dao
method as peruser id
parameter.Instead of getting token from database and matching with current token you can use cache. create your own cache object like
Map
or a staticstring
, which will have the latest token. and you can direct compare incoming token with this token from cache. no need to hit database for every time.