Spring Boot 集成 Spring Security 使用
创建时间:2018-05-19  访问量:14052  7  2

Spring Boot 集成 Spring Security 使用

CustomLogoutHandler.java

自定义注销处理器

package com.zxstrive.fight.sys.extend.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.csrf.DefaultCsrfToken;

import net.sf.json.JSONObject;

public class CustomLogoutHandler implements LogoutSuccessHandler {

	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		DefaultCsrfToken _csrf = (DefaultCsrfToken) request.getAttribute("_csrf");
		String requestType = request.getHeader("X-Requested-With");
		if("XMLHttpRequest".equalsIgnoreCase(requestType)) {
			try (PrintWriter out = response.getWriter()){
				JSONObject json = new JSONObject();
				json.element("status", "success");
				json.element("_csrf", _csrf.getToken());
				out.write(json.toString());
				out.flush();
				out.close();
			}catch(Exception e) {
				 
			}
		}else {
			response.sendRedirect(request.getContextPath()+"/");
		}
	}

}

获取原_csrf的原因是,在注销后_csrf会改变,会影响以后的访问。