com.feingto.cloud.security.GwAccessDeniedHandler Maven / Gradle / Ivy
package com.feingto.cloud.security;
import com.feingto.cloud.core.web.WebResult;
import com.feingto.cloud.kit.HttpKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 权限验证失败处理器
*
* @author longfei
*/
@Slf4j
public class GwAccessDeniedHandler implements AccessDeniedHandler {
private String errorPage;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
log.warn(accessDeniedException.getMessage());
if (HttpKit.isAjaxWithRequest(request)) {
PrintWriter writer = response.getWriter();
writer.print(WebResult.error(accessDeniedException.getMessage()).put("code", HttpServletResponse.SC_FORBIDDEN));
writer.close();
} else {
if (!response.isCommitted()) {
if (errorPage != null) {
request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
dispatcher.forward(request, response);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
}
}
}
}
public void setErrorPage(String errorPage) {
if ((errorPage != null) && !errorPage.startsWith("/")) {
throw new IllegalArgumentException("errorPage must begin with '/'");
}
this.errorPage = errorPage;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy