登录或认证失败返回自定义JSON

2022-09-05 SpringSecurity

上文我们已经完成了登录功能,在认证失败或者是授权失败的情况下,返回是数据是json格式的,这样可以让前端能对响应进行统一的处理。要实现这个功能我们需要知道SpringSecurity的异常处理机制。

# 自定义认证失败处理器

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //1.设置响应编码
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();

        // 企业开发中,会统一JSON数据格式的处理,这里为了讲述SpringSecurity会尽量少的耦合其他代码
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("msg", "认证失败,请重新登录");
        // 我用的Hutool工具包的JSON处理方法,您可以使用fastjson或其他工具类库
        String res = JSONUtil.toJsonStr(resultMap);
        out.write(res.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}

# SpringSecurity配置类配置认证失败处理器

@Configuration
public class SecurityConfig {

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // ……
        
        // 登录失败处理器
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
        return http.build();
    }
}
上次更新: 1 年前