美文网首页
SpringOauth2-资源服务器,怎么自定义token失效的

SpringOauth2-资源服务器,怎么自定义token失效的

作者: 胡浩8880 | 来源:发表于2020-03-03 16:22 被阅读0次

    默认情况下,token过期或失效的返回内容如下

    {   

    "error": "invalid_token",   

    "error_description": "6610c99d-505c-4f80-927c-a5d23c0e54cb"

    }

    因为当前对接需求,需要把默认的返回内容修改为

     "code": 10003, 

     "msg": "token失效"

    百思不得其解,准备放弃,请求大神的时候,找到了解决办法

    直接干货

    第一个类:无效token 异常重写

    @Component

    public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private static final int UN_LOGIN = 10002;

    private static final int INVALID_TOKEN = 10003;

    @Override

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws ServletException {

    Map<String, Object> map = new HashMap<>();

    Throwable cause = authException.getCause();

    if (cause instanceof InvalidTokenException) {

    //401

    map.put("code", INVALID_TOKEN);

    map.put("msg", "无效的token");

    } else {

    //401

    map.put("code", UN_LOGIN);

    map.put("msg", "访问此资源需要完全的身份验证");

    }

    response.setContentType("application/json");

    response.setStatus(HttpServletResponse.SC_OK);

    try {

    ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(response.getOutputStream(), map);

    } catch (Exception e) {

    throw new ServletException();

    }

    }

    第二个类:权限不足异常类重写

    @Component

    public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private static final int UN_LOGIN = 10002;

    @Override

    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {

    response.setContentType("application/json;charset=UTF-8");

    Map<String, Object> map = new HashMap<>();

    map.put("code", UN_LOGIN);

    map.put("msg", "权限不足");

    ObjectMapper mapper = new ObjectMapper();

    response.setContentType("application/json");

    response.setStatus(HttpServletResponse.SC_OK);

    response.getWriter().write(mapper.writeValueAsString(map));

    }

    }

    关键配置,在资源配置类中,重写方法:

    @Override

    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

    super.configure(resources);

    resources

    .authenticationEntryPoint(new AuthExceptionEntryPoint())

    .accessDeniedHandler(new CustomAccessDeniedHandler());

    }

    大功告成,看看您的结果把

    相关文章

      网友评论

          本文标题:SpringOauth2-资源服务器,怎么自定义token失效的

          本文链接:https://www.haomeiwen.com/subject/vtuhlhtx.html