这篇文章主要介绍shiro与spring security怎么用自定义异常处理401错误,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
shiro与spring security自定义异常处理401
背景
现在是前后端分离的时代,后端必然要统一处理返回结果,比如定义一个返回对象
public class ResponseData<T> { public String rtnCode; public String rtnMsg; public T rtnData;
对于所有异常都有对应的rtnCode对应,而不需要框架默认处理如返回
这时候前端同学就不开心了,都已经有rtnCode了,为啥http的status还要弄个401而不是200。
解决方案
一般的业务异常在springboot项目中新建一个统一处理类去处理即可,如
@ControllerAdvicepublic class DefaultExceptionHandler { @ExceptionHandler({Exception.class}) @ResponseStatus(HttpStatus.OK) @ResponseBody public ResponseData allException(Exception e) {
大部分情况都能捕获到从而如期返回json对象数据,但是某些权限框架抛出的异常如401等等,不会被拦截到,这时候就需要再建一个类去处理这种情况,代码如下
package com;import com.vo.ResponseData;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.web.ErrorAttributes;import org.springframework.boot.autoconfigure.web.ErrorController;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.Map;@RestControllerpublic class CustomErrorController implements ErrorController {private static final String PATH = "/error"; @Autowired private ErrorAttributes errorAttributes; @RequestMapping(value = PATH) ResponseData error(HttpServletRequest request, HttpServletResponse response) { // Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring. // Here we just define response body. Map<String, Object> errorMap = getErrorAttributes(request); ResponseData d= new ResponseData(response.getStatus()+"", errorMap.get("message").toString()); response.setStatus(HttpServletResponse.SC_OK); return d; } @Override public String getErrorPath() { return PATH; } private Map<String, Object> getErrorAttributes(HttpServletRequest request) { RequestAttributes requestAttributes = new ServletRequestAttributes(request); return errorAttributes.getErrorAttributes(requestAttributes, false); }}
SpringBoot整合Shiro自定义filter报错
No SecurityManager accessible to the calling code...
最近在用springboot整合shiro,在访问时出现了No SecurityManager accessible to the calling code…
报错:
产生原因
自定义的SysUserFilter加载顺序在ShiroFilter之前,导致出现No SecurityManager accessible to the calling code…
解决办法
shiroFilter()的加载先于自定义的SysUserFilter
以上是“shiro与spring security怎么用自定义异常处理401错误”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!