java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Security LogoutSuccessHandler注销成功

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

作者:杜小舟

这篇文章主要介绍了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();
    }
    
}

总结

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

您可能感兴趣的文章:
阅读全文