Spring Security之LogoutSuccessHandler注销成功操作方式

 更新时间:2024年08月01日 14:56:04   作者:杜小舟  
这篇文章主要介绍了Spring Security之LogoutSuccessHandler注销成功操作方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

前言

LogoutSuccessHandler 接口定义了在用户成功注销后执行的操作。

当用户从应用程序中注销时,这个处理器被触发。

它允许我们开发者自定义注销成功后的行为,例如重定向到特定页面、显示注销确认信息、进行清理工作或其他自定义逻辑。

接下来先简单介绍官方的处理器,再自己自定义一个处理器。

官方给的处理器

SimpleUrlLogoutSuccessHandler

注销成功后重定向到一个URL地址。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);

        http
                // 退出登录
                .logout()
                // 退出登录成功后处理器
                .logoutSuccessHandler(logoutSuccessHandler());
    }

    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
        // 注销成功后重定向的地址
        logoutSuccessHandler.setDefaultTargetUrl("/logout");
        return logoutSuccessHandler;
    }

ForwardLogoutSuccessHandler

注销成功后转发到一个URL地址。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);

        http
                // 退出登录
                .logout()
                // 退出登录成功后处理器
                .logoutSuccessHandler(logoutSuccessHandler());
    }

    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
    	// 转发地址
        return new ForwardLogoutSuccessHandler("/logout");
    }

HttpStatusReturningLogoutSuccessHandler

不做重定向也不做转发,而是返回一个指定的HTTP状态码。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);

        http
                // 退出登录
                .logout()
                // 退出登录成功后处理器
                .logoutSuccessHandler(logoutSuccessHandler());
    }
    
    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        // 也可以指定其他状态码
        return new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK);
    }

DelegatingLogoutSuccessHandler

DelegatingLogoutSuccessHandler 用于处理用户注销成功后根据不同的请求条件选择并执行相应的 LogoutSuccessHandler。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);

        http
                // 退出登录
                .logout()
                // 退出登录成功后处理器
                .logoutSuccessHandler(logoutSuccessHandler());
    }

    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler = new LinkedHashMap<>();
        // 配置不同的RequestMatcher和对应的LogoutSuccessHandler
        // 配置在 /admin/** 路径下退出登录匹配的 SimpleUrlLogoutSuccessHandler
        SimpleUrlLogoutSuccessHandler simpleUrlLogoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
        simpleUrlLogoutSuccessHandler.setDefaultTargetUrl("/admin-logout");
        matcherToHandler.put(new AntPathRequestMatcher("/admin/**"), simpleUrlLogoutSuccessHandler);

        // 配置在 /user/** 路径下退出登录匹配的 ForwardLogoutSuccessHandler
        matcherToHandler.put(new AntPathRequestMatcher("/user/**"), new ForwardLogoutSuccessHandler("/user-logout"));

        DelegatingLogoutSuccessHandler handler = new DelegatingLogoutSuccessHandler(matcherToHandler);
        // 配置默认的 ForwardLogoutSuccessHandler
        handler.setDefaultLogoutSuccessHandler(new ForwardLogoutSuccessHandler("/default-logout"));
        
        return handler;
    }

自定义处理器

package com.security.handler.logout;

import com.alibaba.fastjson2.JSON;
import com.security.controller.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
@Slf4j
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("退出登录成功 ...");

        /**
         * 设置响应状态值
         */
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String json = JSON.toJSONString(
                ResponseResult.builder()
                        .code(200)
                        .message("退出登录成功!")
                        .build());

        // JSON信息
        response.getWriter().println(json);
    }
}
package com.security.config;

import com.security.handler.logout.LogoutSuccessHandlerImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;


@Configuration
@EnableWebSecurity
// 开启限制访问资源所需权限
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurationTest extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);

        http
                // 退出登录
                .logout()
                // 退出登录成功后处理器
                .logoutSuccessHandler(logoutSuccessHandler());
    }

    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        return new LogoutSuccessHandlerImpl();
    }
    
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。 

相关文章

  • SpringBoot整合Web之CORS支持与配置类和 XML配置及注册拦截器

    SpringBoot整合Web之CORS支持与配置类和 XML配置及注册拦截器

    这篇文章主要介绍了SpringBoot整合Web开发中CORS支持与配置类和 XML配置及注册拦截器的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • Java判断ip是否为IPV4或IPV6地址的多种方式

    Java判断ip是否为IPV4或IPV6地址的多种方式

    本文主要介绍了Java判断ip是否为IPV4或IPV6地址的多种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • Java中的Native方法

    Java中的Native方法

    这篇文章主要介绍了Java中的Native方法,在本文中,我们将看到java中本机native方法的介绍。我们将看到它的基本语法及其工作原理。将有java代码示例展示native本机方法的使用,下面来看看文章的具体介绍
    2021-12-12
  • Java使用Instant时输出的时间比预期少了八个小时

    Java使用Instant时输出的时间比预期少了八个小时

    在Java中,LocalDateTime表示没有时区信息的日期和时间,而Instant表示基于UTC的时间点,本文主要介绍了Java使用Instant时输出的时间比预期少了八个小时的问题解决,感兴趣的可以了解一下
    2024-09-09
  • SpringBoot2底层注解@ConfigurationProperties配置绑定

    SpringBoot2底层注解@ConfigurationProperties配置绑定

    这篇文章主要介绍了SpringBoot2底层注解@ConfigurationProperties配置绑定,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • java实现获取用户的MAC地址

    java实现获取用户的MAC地址

    本文给大家汇总介绍了下使用java实现获取客户端用户的MAC地址的方法,当然最后一种更全面一些,有需要的小伙伴们可以根据需求自由选择。
    2015-10-10
  • Java List 用法详解及实例分析

    Java List 用法详解及实例分析

    这篇文章主要介绍了Java List 用法详解及实例分析的相关资料,需要的朋友可以参考下
    2017-07-07
  • 浅谈java安全编码指南之堆污染

    浅谈java安全编码指南之堆污染

    什么是堆污染呢?是指当参数化类型变量引用的对象不是该参数化类型的对象时而发生的。我们知道在JDK5中,引入了泛型的概念,在创建集合类的时候,指定该集合类中应该存储的对象类型。如果在指定类型的集合中,引用了不同的类型,那么这种情况就叫做堆污染。
    2021-06-06
  • Java Session会话追踪原理深入分析

    Java Session会话追踪原理深入分析

    web开发阶段我们主要是浏览器和服务器之间来进行交互。浏览器和服务器之间的交互就像人和人之间进行交流一样,但是对于机器来说,在一次请求之间只是会携带着本次请求的数据的,但是可能多次请求之间是会有联系的,所以提供了会话机制
    2022-11-11
  • 如何通过Java实现修改视频分辨率

    如何通过Java实现修改视频分辨率

    Java除了可以修改图片的分辨率,还可以实现修改视频的分辨率,这篇文章就将带大家学习如果编写这一工具类,感兴趣的同学可以了解一下
    2021-12-12

最新评论