In the previous tutorial, I introduced you to the basic authentication and authorization in Spring Security. If you pay attention, you will see and wonder that after logging in to the application, how will we logout? I will guide you on how to logout in Spring Security in this tutorial!
I also have a simple Spring Security application as follows:
With Spring Security’s configuration file, the content is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security https://www.springframework.org/schema/security/spring-security.xsd"> <http /> <user-service> <user name="khanh" password="{noop}123456" authorities="ROLE_USER" /> </user-service> </beans:beans> |
To logout in Spring Security, we will only need to call the “/logout” request provided by Spring Security by default. Then, all user login information will be cleared and our application will redirect itself to the “/login?logout” request.
To see this clearly, let’s edit the home.jsp file in the folder src/main/webapp/WEB-INF/views/ to add a link for the “/logout” request as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ page session="false"%> <html> <head> <title>Home</title> </head> <body> <h1>Hello world!</h1> <P>The time on the server is ${serverTime}.</P> <a href="<c:url value="/logout" />">Logout</a> </body> </html> |
Here, I use the JSTL library to add this link.
The results after running the application, accessing the application, logging in with the “khanh” user will be as follows:
Now, if you click on the Logout link, you will see the following result:
This is the confirm window that asking you really want to logout or not? Click Log Out button to confirm your need!
The following result will be as follows: