- Logout in Spring Boot
- Table of contents
- Solution
- The meanings of source code
- Spring Security Logout
- Spring Security Logout
- 1. Application Setup
- 2. Logout Configuration
- 3. Spring Security Logout UI
- 3.1. Logout Using GET
- 4. Testing Logou t
- Summary
- Spring Security Logout doesn’t work with Spring 4 CORS
- 2 Answers 2
- Logout в Spring Security
Logout in Spring Boot
In web development, we usually cope with some problems about logging out a website. After logging out, we have to set the invalidation state of session, and delete our cookies …
But in Spring Boot, we do not have a specific solution for this problem.
So, in this article, we will discuss about logout problem in spring boot.
Table of contents
Solution
First solution, define in configure() method directly.
We can use the following code segment:
So, we will explain how Spring Security logout based on AntPathRequestMatcher class.
While going to the URL /logout , an object of AntPathRequestMatcher class will compare its link with link that is routed. If matched, Spring security will log out and implement sequence actions such as invalidateHttpSession() , deleteCookies() , and logoutSuccessUrl() .
We will not set up for logout information in configure() method of WebSecurityConfig class.
Then, we will process /logout in handling method of Controller .
With this way, we will get information about user’s authentication by using SecurityContextHolder.getContext().getAuthentication() .
If user was, then, we called SecurityContextLogoutHandler().logout(request, response, auth) to logout user properly.
The logout call performs following:
- Invalidates HTTP session, then unbinds any objects bound to it.
- Removes the Authentication from the SecurityContext to prevent issues with concurrent requests.
- Explicitly clears the context value from the current thread.
In this solution, we will still use configure() method, but there are some changes in fetchSignoutSite() method in Controller class.
If we are using this fetchSignoutSite() method, we don’t need to include the first solution in Spring security config. By using this solution, we can add extra action to do before and after logout done. But, to use this solution, just call the /logout url and user will be logout manually. This solution will invalidate session, clear spring security context and cookies.
If we are using RequestMethod.POST , we need to include the csrf key as a post. The alternative way is to create a form with hidden input csrf key. This is some example of auto generated logout link with JQuery.
We just need to create hyperlink «` >Logout to use it.
If we are using RequestMethod.GET , just include a csrf key as a parameter in our link like this:
Note: We have to go to a page with link /logout .
We can do that by defining anchor with the href = «@» in thymeleaf:
The meanings of source code
Using AntPathRequestMatcher class
Matcher will compares a pre-defined ant-style pattern against the URL (servletPath + pathInfo) of an HttpServletRequest . The query string of the URL is ignored and matching is case-insensitive or case-sensitive depending on the arguments passed into the constructor.
Using a pattern value of /** or ** is treated as a universal match, which will match any request. Patterns which end with /** (and have no other wildcards) are optimized by using a substring match — a pattern of /aaa/** will match /aaa, /aaa/ and any sub-directories, such as /aaa/bbb/ccc.
For all other cases, Spring’s AntPathMatcher is used to perform the match.
Note: Use org.springframework.security.web.util.matcher.AntPathRequestMatcher , and not the deprecated org.springframework.security.web.util.AntPathRequestMatcher class.
Use SecurityHolderContext , SecurityContext class
We will have two declarations of SecurityHolderContext , SecurityContext class.
The interface SecurityContext will define the minimum security information associated with the current thread of execution.
And the security context is stored in a SecurityContextHolder class.
SecurityContext is centering interface of Spring Security, saves all information that is relevant to the security in application. When we start Spring Security, SecurityContext will be initialize.
We can not access directly into SecurityContext , but we can use SecurityContextHolder class. This class will contain the current SecurityContext of application, which includes principal that is interacting with application.
Spring Security will use Authentication object to represent their information. The following code will help us get username and password that is typed from a user.
Источник
Spring Security Logout
In the last article, we learned how to create login using spring security. In this article, we will learn how to perform spring security logout. Spring security provides a build in capabilities to handle most of the complex tasks during the logout.
Spring Security Logout
Logout id an integral part of any secure application. Logout ensure that all sensitive information is removed or invalidated once customer performs the logout. Spring security store authentication information in the session. Spring security automatically handles the following tasks for the application.
- Invalidating the HTTP Session.
- Cleaning up any RememberMe authentication configuration.
- Clearing the SecurityContextHolder.
- Redirect user to the configured page.
In this post, we will inspect the logout functionality using spring security and spring boot along with the extension points.
1. Application Setup
Let’s start by creating a sample application. You can also download the complete application from our GitHub repository. If needed, you can use IDE or Spring initializr to create the application. We are adding the following dependencies for our application by utilizing Spring boot auto configuration feature.
- Spring security auto configuration.
- Spring web starter.
- Thymeleaf.
This is how the pom.xml look like:
2. Logout Configuration
Since Spring security will handle most of the heavy lifting during the logout process, we only need to configure few details our custom security configuration class extending the WebSecurityConfigurerAdapter. Here is the basic configuration to enable the logout feature:
There are few things which we should keep in mind when enabling the logout feature:
- On successful logout, customer by default redirected to the /login?logout . Spring security provides flexibility to change the URL.
- If CSRF protection is active (default), Spring security expects the logout request must of POST type, we can use the GET logout request by disabling the CSRF protection.
Here is the complete reference in case you need more control on the logout process:
- logoutSuccessURL – help to redirect the user to a landing page post logout, the default The default is /login?logout (In our case, we are redirecting to the home page).
- logoutSuccessHandler – Handler, which triggers once the logout is complete. We can use this to handle redirection or forwarding to the destination.Keep in mind that the logoutSuccessUrl() will be ignored if we configure the logoutSuccessHandler .
- invalidateHttpSession – Controls if HTTP session should be invalided. The default value is true.
- deleteCookies – Delete any secure cookies (in case we are setting during the login.)
To customize logout functionality, you can add LogoutHandler and/or LogoutSuccessHandler implementations.
3. Spring Security Logout UI
We need to give the option to the customer to click on the logout link. Spring security provides following 2 options:
- Perform the POST logout (this is default and recommended.)
- Perform the GET logout by disabling CSRF feature.
We are using the Thymeleaf as the templating engine, please change the code as per your UI.
We are doing a POST logout request. Also remember following:
- Your request for action should be /logout. This is the logout handler from Spring security.
We are using sec:authorize=»isAuthenticated()
To ensure that logout link is only visible to the logged in user. If you are using Thymeleaf, you need to add additional dependency in your pom.xml to enable suppport for Spring Security Dialect using the Thymeleaf – Spring Security integration modules.
3.1. Logout Using GET
If you can’t perform a POST request and like to fall back to GET logout request, you need the following changes in your application.
- Disable CSRF.
- Conver POST request to GET on UI.
4. Testing Logou t
Our configuration and changes are complete, start the application, once application is up and running do a login.
Logged In Screen:
If we check the cookies, we will see the following cookies:
- JSESSIONID .
- Custom Cookie (Stored during login process)
When we perform the logout, Spring Security will invalidate the session and delete any additional cookie (if we configure it in the logout configuration). To check this, perfrom the following additional steps
- Note down the JSESSIONID id after the login.
- Do a logout and check the JSESSIONID again, both ID will be different.
Here is the screen after logout:
dummyCookie is no longer available post logout since we told Spring security to delete it on successful logout.
Summary
In this post, we looked at the Spring security logout feature. Spring security provides build in support for the logout with a small configuration and code changes. At the same time it’s flexible enough to allow you to customize the logout behaviour for your application. In Summary:
- How to perfrom the logout in Spring application.
- What are the configuration required to enable logout feature?
- How to customize the logout behaviout by injecting your own logout success handlers.
This post is part of our Spring security course and the code base is available on the GitHub
Источник
Spring Security Logout doesn’t work with Spring 4 CORS
Recently I tried the new built-in CORS-Support in Spring 4. This feature is great and I want to implement this in my Spring Boot / AngularJS application.
All request works fine but I can’t logout my user because the OPTIONS -Request to /logout is handled by Spring Security.
Is it possible to handle the OPTIONS -Request before Spring Security or should I attach CORS-Headers in LogoutSuccessHandler ?
2 Answers 2
When working with Spring Security, it is recommended to use CorsFilter. You will want to ensure that you order the CorsFilter before Spring Security’s FilterChainProxy .
You can refer to Spring Data Rest and Cors for details on using CorsFilter . For this issue, the difference is likely that you want to register only for the logout URL. For example:
I know this is a bit late. I was having the same problem with /logout being rejected by my Angular2 browser app because of the CORS header Access-Control-Allow-Origin not being returned in the /logout response. The /logout seems to be processed before the CORS filter is reached so doesn’t get the header. I tried the solution above but it didn’t work for me. So, i tried this next solution and it works great:
- Create a LogoutHandler implementation class and implement logout()
- Create a LogoutSuccessHandler implementation class and implement onLogoutSuccess()
- Wire the two classes to the Spring security configuration
Turns out I didn’t need the LogoutSuccessHandler class, just the LogoutHandler. The LogoutSuccessHandler (not shown) is just an empty implementation with a logging statement in it. The LogoutHandler is below. This is a snippet of a Spring-boot REST app coded in Groovy (very similar to java)
Then wire this together in your security configuration class that extends WebSecurityConfigurerAdapter like this below. The last part, showing the logout section is the relevant part in the standard configure() method.
Источник
Logout в Spring Security
В этой статье будет рассказано о возможности выхода пользователя из системы (logout) и связанные с этим моменты в Spring Security версии 3.x.
Самый простой способ выйти для авторизированного пользователя — это использовать ссылку с действием /j_spring_security_logout. Это стандартное действие Spring Security, благодаря которому все действия по выходу пользователя из системы берет на себя Spring Security. Пример кода:
Но давайте глубже разберемся в вопросе Logout. Как основа в этой статье будет использоваться пример из первой части статьи «Введение в Spring Security. Hello World!». Создайте проект, следуя инструкциям из статьи, или скачайте файл проекта для его использования в этой статье.
Первое, что сделаем, — изменим код таким образом, что ссылка Logout будет отображаться только авторизированным пользователям. Самый простой способ сделать это — использовать теги Spring Security. jsp-страница будет выглядеть следующим образом:
Для того чтобы использовать теги Spring Security, необходимо добавить зависимость spring-security-taglibs в файл pom.xml:
Весь файл pom.xml выглядит так:
Теперь в jsp-файлах есть возможность использовать теги Spring Security. Нам понадобится только один из них — authorize (остальным тегам будет посвящена отдельная статья). Добавьте в jsp-файле, в котором Вы хотите использовать ссылку Logout, следующую библиотеку:
А ссылка будет выглядеть так:
Содержимое тега sec:authorize будет отображено только если пользователь вошел в систему, что описывается выражением isAuthenticated().
Тем не менее, чтобы использовать выражение isAuthenticated() в jsp-файле необходимо изменить конфигурацию безопасности (файл application-security.xml) следующим образом. Блок http:
заменить на следующий код
Всё дело в атрибуте use-expressions тега http. Этим тегом в Spring Security обозначается, что будут использоваться выражения. Их (выражений) существует множество и следующая часть статей о Spring Security будет посвящена им.
Также есть возможность изменить адрес /j_spring_security_logout для выхода из системы. Всё, что нужно, — добавить в тег http тег logout с атрибутом logout-url:
Теперь jsp-страницу можно изменить адрес для Logout:
А ссылка будет выглядеть так:
У тега logout есть еще несколько полезных атрибутов:
Атрибут delete-cookies — это список куки (cookies), разделенный запятыми, которые будут удалены, когда пользователь выйдет из системы.
Атрибут invalidate-session — если Вы хотите аннулировать сессию при выходе пользователя из системы, установите этот атрибут в true, иначе — false. По умолчанию — true.
Атрибут logout-success-url — адрес, на который будет перенаправлен пользователь после того, как он вышел из системы. По умолчанию — корень «/».
Атрибут logout-url — адрес, используя который пользователь выйдет из системы. По умолчанию — «/j_spring_security_logout».
Атрибут success-handler-ref — сервис, унаследованный от LogoutSuccessHandler, который контролирует навигацию пользователя после того, как последний вышел из системы.
Рассмотрим пример с последним атрибутом success-handler-ref. Изменим тег logout следующим образом:
Код сервиса CustomLogoutSuccessHandler представлен ниже:
Класс этого сервиса должен быть унаследован от SimpleUrlLogoutSuccessHandler. Если Вы хотите изменить логику выхода пользователя из системы, необходимо переопределить метод onLogoutSuccess(). Также в этом методе Вы можете произвести необходимые Вам действия для обработки выхода пользователя из системы.
В нашем примере если имя пользователя user, то он перенаправляется на адрес «/logout/user», все остальные пользователи после выхода попадают на домашнюю страницу.
Чтобы этот код работал необходимо сделать адрес «/logout/user» доступным для незарегестрированных пользователей. То есть, добавить в application-security.xml следующую строку:
Также потребуется немного изменить структуру конфигурации проекта:
Источник