美文网首页
Spring Security 用户没有权限返回错误

Spring Security 用户没有权限返回错误

作者: and天神 | 来源:发表于2018-10-25 20:17 被阅读0次

Spring Security  通过  PreAuthorize 注解可以控制用户的权限 重写 implements   PermissionEvaluatorhas  的 Permission()方法 通过 返回的结果判断用户是否有权限,如果没有回返回系统 自定义的错误页面 但是我们想返回错误信息 所以要重新拦截 和写一个自定义的错误信息

WebSecurityConfigurerAdapter   下的  configure     http

.authorizeRequests()

.anyRequest()

.authenticated()

.and()

// 配置被拦截时的处理  这个位置很关键

        .exceptionHandling()

//添加无权限时的处理

        .accessDeniedHandler(accessDeniedHandler)

@Component

public class MyAccessDeniedHandlerimplements AccessDeniedHandler {

@Override

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

//返回json形式的错误信息

        response.setCharacterEncoding("UTF-8");

response.setContentType("application/json");

response.getWriter().println("{\"code\":403,\"message\":\"小弟弟,你没有权限访问呀!\",\"data\":\"\"}");

response.getWriter().flush();

}

}

2个类的代码就行了

相关文章

网友评论

      本文标题:Spring Security 用户没有权限返回错误

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