今天的内容比较简单…现在项目中,对权限控制了之后,如果访问到没有权限的接口,提示并不是很友好
想着利用自定义拦截器进行处理一下,后想要得到的效果如下
这样看起来就友好一点了~
自定义拦截器
package com.example.security.Exception;
import com.alibaba.fastjson.JSON;
import com.example.security.util.RetCode;
import com.example.security.util.RetResult;
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;
/**
* @Autoor:杨文彬
* @Date:2019/1/28
* @Description:
*/
@Component
public class RewriteAccessDenyFilter implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
RetResult retResult = new RetResult(RetCode.NODEFINED.getCode(),"抱歉,您没有访问该接口的权限");
httpServletResponse.setContentType("application/json;charset=utf-8");
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.getWriter().write(JSON.toJSONString(retResult));
}
}
主要的思路是重写一个拦截器,实现AccessDeniedHandler
,自定义返回格式,然后使用阿里巴巴的fastjson
处理下返回数据。
然后就需要把这个拦截器加入到之前我们设置的WebSecurity
配置类中,主要代码是后一行
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
http.exceptionHandling().accessDeniedHandler(rewriteAccessDenyFilter);
同时需要在这个类中注入一下就好了~
//自定义无权限访问拦截器
@Autowired
private RewriteAccessDenyFilter rewriteAccessDenyFilter;
增加的pom依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>