Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and destroy session in Spring REST Webservice called from Mobile client

I have Spring REST webserivce Now from a mobile client webservice is getting called. First, login method is called for log in succes or failure based on sent value userid and password.

      @RequestMapping(value = "/login", method = RequestMethod.POST,       headers="Accept=application/json")
     public @ResponseBody List<LogInStatus> getLogIn(@RequestBody LogIn person , HttpServletRequest request) {
              // Call service here
             List<LogInStatus> lList = logInService.getUser(person);
//service method and then in DAO database method is there

             return lList;
     }

Now, for many other call, I need logged in user based values, so need to keep session and need to get current user.And at log out call, need to destroy session. How to do this and achieve,please help with ideas.

like image 748
Pan Avatar asked Oct 27 '14 13:10

Pan


2 Answers

You don't need to create session manually - this is done by servlet container.

You can obtain session from HttpServletRequest

HttpSession session = request.getSession();

or just add it as a method parameter, and Spring MVC will inject it for you:

public @ResponseBody List<LogInStatus> getLogIn(@RequestBody LogIn person , HttpServletRequest request, HttpSession httpSession) 

You then can save user details in session via setAttribute()/getAttribute().

However, you are much better off using Spring Security, which is intended just for the task - see @Pumpkins's answer for references. SecurityContext contains info about currently logged in principal, which you can obtain from SecurityContextHolder

like image 199
Vladimir Avatar answered Sep 23 '22 03:09

Vladimir


You need to integrate spring security in your project and make your rest calls via authentication verifier tokens.

You may refer to the documentation :

http://projects.spring.io/spring-security/

Or this nice tutorial can jumpstart your implementation :

http://www.networkedassets.com/configuring-spring-security-for-a-restful-web-services/

like image 44
Pumpkin Avatar answered Sep 23 '22 03:09

Pumpkin