Spring Security——关闭未认证时重定向(302)到登录页面(loginPage)
问题描述
当访问该web服务的一个请求 /test 且该请求需要用户认证,那么Spring Security会将请求302到通过 httpSecurity.formLogin().loginPage("/login") 设定的页面里。
问题分析
org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer
org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer
org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint
解决方案
httpSecurity.exceptionHandling()//没有认证时,在这里处理结果,不要重定向.authenticationEntryPoint(new AuthenticationEntryPoint() {@Overridepublic void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException authException) throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");resp.setStatus(401);PrintWriter out = resp.getWriter();respBean = RespBean.error("访问失败!");if (authException instanceof InsufficientAuthenticationException) {respBean.setMsg("请求失败,请联系管理员!");}out.write(new ObjectMapper().writeValueAsString(respBean));out.flush();out.close();}});
参考文章
关于SpringSecurity的重定向到loginPage()页面的一个坑
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!





