【Spring Security】LogoutSuccessHandler 注销成功后操作

文章目录

    • 前言
    • 官方给的处理器
      • SimpleUrlLogoutSuccessHandler
      • ForwardLogoutSuccessHandler
      • HttpStatusReturningLogoutSuccessHandler
      • DelegatingLogoutSuccessHandler
    • 自定义处理器


前言

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();
    }
    
}




End


你可能感兴趣的:(#,Spring,Security,spring,java,后端)