Spring相关之SpringSecurity使用(五)
2019-10-12 本文已影响0人
CLee润儒
JSONRespEntity
package com.lee.security.comoon;
/**
*
* @ClassName: JSONRespEntity
* @Description: 响应实体
*/
public class JSONRespEntity<T>
{
/**
* 返回状态码 // 0代表成功,else失败,建议用-1
*/
private int status;
/**
* 返回实体
*/
private T data;
/**
* 错误描述
*/
private String msg;
/**
* 默认构造器
*/
public JSONRespEntity()
{
super();
}
/**
* 只返回错误信息
*
* @param status
*/
public JSONRespEntity(int status)
{
super();
this.status = status;
}
/**
* 返回错误信息和描述
*
* @param status
* @param msg
*/
public JSONRespEntity(int status, String msg)
{
super();
this.status = status;
this.msg = msg;
}
/**
* 有参构造
*
* @param status
* 状态码
* @param data
* 实体
* @param msg
* 错误描述
*/
public JSONRespEntity(int status, T data, String msg)
{
super();
this.status = status;
this.data = data;
this.msg = msg;
}
/**
* @return the status
*/
public int getStatus()
{
return status;
}
/**
* @param status
* the status to set
*/
public void setStatus(int status)
{
this.status = status;
}
/**
* @return the data
*/
public T getData()
{
return data;
}
/**
* @param data
* the data to set
*/
public void setData(T data)
{
this.data = data;
}
/**
* @return the msg
*/
public String getMsg()
{
return msg;
}
/**
* @param msg
* the msg to set
*/
public void setMsg(String msg)
{
this.msg = msg;
}
}
JsonResponse
package com.lee.security.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lee.security.comoon.JSONRespEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 由于Response无法直接向客户端 发送json 所以该工具类使用objectMapper向前端书写json
*/
@Component
public class JsonResponse {
public static Logger logger = Logger.getLogger(JsonResponse.class);
@Autowired
private ObjectMapper objectMapper;
/**
* 给客户端返回json应答
*
* @param resp
* @param entity
*/
public void writeJsonResponse(HttpServletResponse resp, JSONRespEntity entity)
{
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/json;charset=UTF-8");
try
{
objectMapper.writeValue(resp.getWriter(), entity);
} catch (IOException e)
{
logger.error("转换应答实体为JSON格式时异常," + e.getMessage());
}
}
}
AccessDeniedHandler
package com.lee.security.springsecurity;
import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 授权失败处理器
*/
@Component(value = "myAccessDeniedHandler")
public class MyAccessDeniedHandler implements AccessDeniedHandler
{
@Autowired
private JsonResponse jsonResponse;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException
{
JSONRespEntity<Object> entity = new JSONRespEntity<>();
entity.setStatus(-998);
entity.setMsg("无操作权限!");
jsonResponse.writeJsonResponse(response,entity);
}
}
AuthenticationEntryPoint
package com.lee.security.springsecurity;
import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
*
* 未登录或session已失效
*/
@Component(value = "myAuthenticationEntryPoint")
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint
{
@Autowired
private JsonResponse jsonResponse;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException
{
JSONRespEntity<Object> entity = new JSONRespEntity<>();
entity.setStatus(-997);
entity.setMsg("请登录系统!");
jsonResponse.writeJsonResponse(response,entity);
}
}
SimpleUrlAuthenticationFailureHandler
package com.lee.security.springsecurity;
import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
*
* 登录失败处理器
*
*/
@Component(value = "myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Autowired
private JsonResponse jsonResponse;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
JSONRespEntity<Object> entity = new JSONRespEntity<>();
entity.setStatus(-1);
entity.setMsg("登录失败!" + (exception.getMessage()));
jsonResponse.writeJsonResponse(response,entity);
}
}
SavedRequestAwareAuthenticationSuccessHandler
package com.lee.security.springsecurity;
import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 认证成功处理器
*
*/
@Component(value = "myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private static Logger logger = Logger.getLogger(MyAuthenticationSuccessHandler.class);
@Autowired
private JsonResponse jsonResponse;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) {
//登录成功后我们先拿到当前登录用户的信息 共前台使用
MyAuthenticationToken authenticationToken = (MyAuthenticationToken) authentication;
SpringSecurityUserInfo springSecurityUserInfo = authenticationToken.getSpringSecurityUserInfo();
// 登录成功后要返回的json
JSONRespEntity<Object> entity = new JSONRespEntity<>();
entity.setStatus(0);
entity.setMsg("登录成功!");
entity.setData(springSecurityUserInfo);
//这列将对当前用户信息 放心session redis 等等 比如说移动application.properties端的时候 以后做session共享等功能都可以在这里实现
//这里我们将用户信息直接放在security的上下文里面 后续业务需要使用的话 我们创建一个工具类就可以直接拿出当前用户信息
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(authentication);
jsonResponse.writeJsonResponse(response,entity);
}
}
LogoutHandler
package com.lee.security.springsecurity;
import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component(value = "myLogoutHandler")
public class MyLogoutHandler implements LogoutHandler {
public static Logger logger = Logger.getLogger(MyLogoutHandler.class);
@Autowired
private JsonResponse jsonResponse;
@Override
public void logout(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) {
JSONRespEntity<Object> entity = new JSONRespEntity<>();
entity.setStatus(0);
entity.setMsg("已成功退出登录!");
jsonResponse.writeJsonResponse(resp,entity);
}
}