spring security oauth2.0 前后分离注销(登出) 解决方案

spring security实现注销功主要处理类是LogoutFilter,LogoutHandler,LogoutSuccessHandler

先来看接口:LogoutHandler

/**
 * Indicates a class that is able to participate in logout handling.
 *
 * <p>
 * Called by {@link LogoutFilter}.
 *
 * @author Ben Alex
 */
public interface LogoutHandler {
	// ~ Methods
	// ========================================================================================================

	/**
	 * Causes a logout to be completed. The method must complete successfully.
	 *
	 * @param request the HTTP request
	 * @param response the HTTP response
	 * @param authentication the current principal details
	 */
	void logout(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication);
}

此接口定义了注销方法。

LogoutSuccessHandler主要定义了注销成功后的操作

public interface LogoutSuccessHandler {

	void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException;

}

如果我们不配置自定义登出配置,则spring默认的配置为:登出url:logout,就是我们直接调用此url即可实现注销,

登录成功后302重定向到login?logout

public LogoutConfigurer<H> logoutUrl(String logoutUrl) {
		this.logoutRequestMatcher = null;
		this.logoutUrl = logoutUrl;
		return this;
	}


好的,我们知道此时知道security默认的注销url,直接调用即可实现注销,然后spring会帮我们重定向到/login?logout,但是一旦前后分离 当统一认证后需要跳回到各自前端服务器url时候,就不能走默认的了,这样就会出现再次登录无法跳回(前端url)的情况,那么我们需要自定义自己的重定向url,

就需要自定义登出handler实现LogoutHandler 然后重定向各自的url

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

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

/**
 * @author zhuxiaomeng
 * @date 2018/6/30.
 * @email 154040976@qq.com
 */
@Component
public class MyLogoutHandler implements LogoutHandler {
	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		try {
			String aa = request.getParameter("aa");//aa即为前端传来自定义跳转url地址
			response.sendRedirect(aa);//实现自定义重定向
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

然后配置到自定义SecurityConfig的覆盖方法configure配置方法中

.and().logout().addLogoutHandler(new MyLogoutHandler())

前端传入这个自定义的url,也就是我们前端服务器的url,来实现自定义注销重定向跳转url。

-踩坑道路的记录2018/7/1

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值