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

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

先来看接口:LogoutHandler

/**
 * Indicates a class that is able to participate in logout handling.
 *
 * 

* 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 logoutUrl(String logoutUrl) {
		this.logoutRequestMatcher = null;
		this.logoutUrl = logoutUrl;
		return this;
	}

spring security oauth2.0 前后分离注销(登出) 解决方案_第1张图片

好的,我们知道此时知道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 [email protected]
 */
@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

你可能感兴趣的:(框架相关,spring,spring,security,oauth2.0)