4 April 2011

How to implement logout in spring with shiro?

 Little history:
I gave up with using spring security ,because i have hundred problems and when i solved one problem,then spring security generate another 10 problems.
I decided to swap to Apache Shiro and everything go smoothly until time.... but i found that implementing log out is a little bit difficult to find on internet,so here i come up with solution:

 So you just add this controller (and change names to make works with your project)

package amazingsoft.mvc.controller; // replace with package in your project


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.ParameterizableViewController;


@Controller
public class LogoutController {


@RequestMapping("/logout.html")  // in my case logout.html is a request came from client to logout,but you can name logout.do or follow your correct convention.
public String handleRequestInternal(HttpServletRequest request, HttpServletResponse response){




  Subject subject = SecurityUtils.getSubject(); //get user
  if (subject != null) {                     //if is not already logged out,then ... log out basterd.
subject.logout();
}


HttpSession session = request.getSession(false); //clear session 
if( session != null ) {
session.invalidate();
}
SecurityUtils.getSubject().logout();
   return "goodbye"; // display goodbye page,where we can share information,that we miss user already
}
}

and then,you can use it on your webiste.
how?
for example:
1)
and add this to your html/jsp
<a href="logout.html">Log Out</a>

2)
as button
<input type="button" value="log out" onclick="window.location = logout.html'"/>

and many ... more efficient ways ....

To makes this work,be sure that:
1)You change some names from above example to your project.
2)Be damn sure,that you configure your spring correctly  (your web.xml)
3)Be damn sure,that you configure your shiro correctly (your application-security.xml or name which you use for your shiro security stuff)

No comments:

Post a Comment