六.Spring Security-认证结果处理

it2025-09-27  1

六.授权结果处理

一.授权失败处理

1.1.概述

当用户请求资源服务的资源时,需要进行用户的认证和授权检查,当认证或授权检查失败,我们需要要返回自己的失败结果信息,可以通过HttpSecurity设置授权失败结果处理器,内部通过 ExceptionTranslationFilter 调用AuthenticationEntryPoint实现匿名用户授权失败结果处理, ExceptionTranslationFilter 通过 AccessDeniedHandler来处理授权失败结果处理。

1.2.定义认证检查失败处理

1.定义AccessDeniedHandler AccessDeineHandler 用来解决认证过的用户访问无权限资源时的异常

public class DefaultAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { String result = JSON.toJSONString(AjaxResult.me().setSuccess(false).setMessage("无访问权限")); response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.print(result); writer.flush(); writer.close(); } }

2.定义AuthenticationEntryPoint AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常

public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { e.printStackTrace(); httpServletResponse.setContentType("application/json;charset=utf-8"); Map<String,Object> result = new HashMap<>(); result.put("success",false); result.put("message","登录失败,用户名或密码错误["+e.getMessage()+"]"); httpServletResponse.getWriter().print(JSONUtils.toJSONString(result)); } }

3.配置异常处理器

//异常处理 httpSecurity.exceptionHandling() .accessDeniedHandler(new DefaultAccessDeniedHandler ()) .authenticationEntryPoint(new MyAuthenticationEntryPoint()) //身份认证验证失败配置
最新回复(0)