spring boot(学习笔记第十三课)
- 传统后端开发模式和前后端分离模式的不同,Spring Security的logout,invalidateHttpSession不好用,bug?
学习内容:
- 传统后端开发模式 vs 前后端分离模式
- Spring Security的logout功能
- invalidateHttpSession不好用,bug?原来还是功力不够!
1. 传统后端开发模式 vs 前后端分离模式
- 传统后端开发模式
上面主要练习传统后端开发模式
,在这种模式下,页面的渲染都是请求后端,在后端完成页面的渲染。认证的页面都是通过https://localhost:8080/loginPage
进行用户名和密码的form
填写,之后重定向到需要认证的资源的页面。
正如spring boot(学习笔记第十二课)的练习的那样,在传统后端开发模式
,需要配置各种页面..formLogin(form -> form.loginPage("/loginPage") .loginProcessingUrl("/doLogin")//这里的url不用使用controller进行相应,spring security自动处理 .usernameParameter("uname")//页面上form的用户名 .passwordParameter("passwd") .defaultSuccessUrl("/index")//默认的认证之后的页面 .failureForwardUrl("/loginPasswordError"))//默认的密码失败之后的页面 .exceptionHandling(exceptionHandling -> exceptionHandling.accessDeniedHandler(new CustomizeAccessDeniedHandler()))
- 前后端分离开发模式
现在web application
的已经过渡到了前后端分离开发模式
,而spring boot security
也兼容这种模式。
接下来通过使用postman
,模拟下前后端分离模式的spring security
开发和使用场景。- 指定认证成功和失败的
handler
注意,这里一定要去掉.loginPage("/loginPage")
.formLogin(form -> form.loginProcessingUrl("/loginProcess")//这里对于前后端分离,提供的非页面访问url .usernameParameter("uname") .passwordParameter("passwd") .successHandler(new SuccessHandler()) .failureHandler(new FailureHandler()))
- 定义认证成功和失败的
handler
//success handler private static class SuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication ) throws IOException { Object principal = authentication.getPrincipal(); httpServletResponse.setContentType("application/json;charset=utf-8"); PrintWriter printWriter = httpServletResponse.getWriter(); httpServletResponse.setStatus(200); Map<String, Object> map = new HashMap<>(); map.put("status", 200); map.put("msg", principal); ObjectMapper om = new ObjectMapper(); printWriter.write(om.writeValueAsString(map)); printWriter.flush(); printWriter.close(); } } //failure handler private static class FailureHandler implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authenticationException ) throws IOException { httpServletResponse.setContentType("application/json;charset=utf-8"); PrintWriter printWriter = httpServletResponse.getWriter(); httpServletResponse.setStatus(401); Map<String, Object> map = new HashMap<>(); map.put("status", 401); if (authenticationException instanceof LockedException) { map
- 指定认证成功和失败的