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

Spring Boot 集成 Spring Security 使用

CustomAuthenticationSuccessHandler.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.AuthenticationSuccessHandler;
import org.springframework.security.web.csrf.DefaultCsrfToken;

import net.sf.json.JSONObject;

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(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)) {
			UserDetailsBean udb = (UserDetailsBean) authentication.getPrincipal();
			try (PrintWriter out = response.getWriter()){
				JSONObject json = new JSONObject();
				json.element("status", "success");
				json.element("obj", udb.getUser());
				json.element("_csrf", _csrf.getToken());
				out.write(json.toString());
				out.flush();
				out.close();
			}catch(Exception e) {
				 
			}
		}else {
			response.sendRedirect(request.getContextPath());
		}
	}

}

区分同步或异步处理方式。