• Spring Security(4)


    您好,我是湘王,这是我的CSDN博客,欢迎您来,欢迎您再来~

    前面的方法中,除了login()方法能成功,另外两个都失败,并不是因为代码问题,而是Spring Security默认是通过Web页面来实现页面逻辑跳转的。但在前后端分离的开发模式中,页面跳转的逻辑后端已经无法直接控制了,而是通过返回状态码由前端来执行跳转。因此,需要对应用进行改造。

    首先自定义认证成功处理器,也就是实现AuthenticationSuccessHandler接口:

    1. /**
    2. * 自定义认证成功处理器
    3. *
    4. * @author 湘王
    5. */
    6. @Component
    7. public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    8. @Override
    9. public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
    10. Authentication authentication) throws IOException, ServletException {
    11. System.out.println("登录成功");
    12. // 前后端分离的调用方式
    13. response.setStatus(HttpStatus.OK.value());
    14. response.setContentType("application/json;charset=UTF-8");
    15. response.getWriter().write("OK");
    16. }
    17. }

    接着来实现之前没有的认证失败处理器AuthenticationFailureHandler:

    1. /**
    2. * 自定义认证失败处理器
    3. *
    4. * @author 湘王
    5. */
    6. @Component
    7. public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    8. @Override
    9. public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
    10. AuthenticationException exception) throws IOException, ServletException {
    11. System.out.println("user or password error");
    12. // 前后端分离的调用方式
    13. response.setStatus(HttpStatus.OK.value());
    14. response.setContentType("application/json;charset=UTF-8");
    15. response.getWriter().write("user or password error");
    16. }
    17. }

    再实现登出处理器LogoutSuccessHandler:

    1. /**
    2. * 自定义登出处理器
    3. *
    4. * @author 湘王
    5. */
    6. @Component
    7. public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
    8. @Override
    9. public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
    10. Authentication authentication) throws IOException, ServletException {
    11. System.out.println("登出成功");
    12. // 前后端分离的调用方式
    13. response.setStatus(HttpStatus.OK.value());
    14. response.setContentType("application/json;charset=UTF-8");
    15. response.getWriter().write("OK");
    16. }
    17. }

    然后修改之前的修改WebSecurityConfiguration,让过滤器中增加对这几个处理器的支持:

    1. // 控制逻辑
    2. @Override
    3. protected void configure(HttpSecurity http) throws Exception {
    4. // 执行UsernamePasswordAuthenticationFilter之前添加拦截过滤
    5. http.addFilterBefore(new CustomInterceptorFilter(), UsernamePasswordAuthenticationFilter.class);
    6. http.authorizeRequests()
    7. .anyRequest().authenticated()
    8. // 设置自定义认证成功、失败及登出处理器
    9. .and().formLogin().loginPage("/login")
    10. .successHandler(successHandler).failureHandler(failureHandler).permitAll()
    11. .and().logout().logoutUrl("/logout").deleteCookies("JSESSIONID")
    12. .logoutSuccessHandler(logoutSuccessHandler).permitAll()
    13. // 跨域访问
    14. .and().cors()
    15. .and().csrf().disable();
    16. }

    现在再次测试LoginController中的登录和登出操作,可以看到它们都能成功执行。目前权限已经做到了与Controller中的业务逻辑无关了。

    但是仅仅做到登录、登出操作肯定是不行的,这连Demo都不如。所以接下里,来看看一个比较核心的问题:用户角色是否有效(不然建角色表干嘛)。

    先在LoginController类中加入下面两个方法:

    1. @GetMapping("/admin")
    2. @PreAuthorize("hasRole('ROLE_ADMIN')")
    3. public String admin() {
    4. return "admin有ROLE_ADMIN角色";
    5. }
    6. @GetMapping("/manager")
    7. @PreAuthorize("hasRole('ROLE_MANAGER')")
    8. public String manager() {
    9. return "manager有ROLE_MANAGER角色";
    10. }

    启动应用,运行postman时会发现:

    1、用admin登录,访问localhost:8080/admin正常,但访问localhost:8080/manager就出现Forbidden错误;

    2、用manager登录,访问localhost:8080/manager正常,而访问localhost:8080/admin也出现Forbidden错误。

    这说明用户角色权限已经起作用了,但显示Forbidden的方式不够友好。所以再来增加一个自定义处理器,也就是实现AccessDeniedHandler接口,让访问拒绝友好一些:

    1. /**
    2. * 自定义访问被拒绝
    3. *
    4. * @author 湘王
    5. */
    6. @Component
    7. public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    8. @Override
    9. public void handle(HttpServletRequest request, HttpServletResponse response,
    10. AccessDeniedException exception) throws IOException, ServletException {
    11. System.out.println("permission denied");
    12. // 前后端分离的调用方式
    13. response.setStatus(HttpStatus.OK.value());
    14. response.setContentType("application/json;charset=UTF-8");
    15. response.getWriter().write("permission denied");
    16. }
    17. }

    然后同样地,要在WebSecurityConfiguration过滤器链中增加这个新增的过滤器:

    1. // 控制逻辑
    2. @Override
    3. protected void configure(HttpSecurity http) throws Exception {
    4. // 执行UsernamePasswordAuthenticationFilter之前添加拦截过滤
    5. http.addFilterBefore(new CustomInterceptorFilter(), UsernamePasswordAuthenticationFilter.class);
    6. http.authorizeRequests()
    7. .anyRequest().authenticated()
    8. // 设置自定义认证成功、失败及登出处理器
    9. .and().formLogin().loginPage("/login")
    10. .successHandler(successHandler).failureHandler(failureHandler).permitAll()
    11. .and().logout().logoutUrl("/logout").deleteCookies("JSESSIONID")
    12. .logoutSuccessHandler(logoutSuccessHandler).permitAll()
    13. // 配置无权访问的自定义处理器
    14. .and().exceptionHandling().accessDeniedHandler(accessDeniedHandler)
    15. .and().cors()
    16. .and().csrf().disable();
    17. }

    再用postman进行测试的时候就能看到,现在的提示现在已经比刚才要友好了。


    感谢您的大驾光临!咨询技术、产品、运营和管理相关问题,请关注后留言。欢迎骚扰,不胜荣幸~

  • 相关阅读:
    MongoDB集群之分片集群 Shard Cluster
    Oracle/PLSQL: Length Function
    Prometheus插件安装(cadvisor)
    八股文第二十一天
    goroutinue
    K8S kubesphere安装mysql
    【Unity】Unity开发进阶(八)Windows解析Excel报错问题、跨平台解析Excel文件
    2023年09月 Scratch(二级)真题解析#中国电子学会#全国青少年软件编程等级考试
    JavaScript(一)
    English Learning - L3 Lesson4 VOA-Food 译文
  • 原文地址:https://blog.csdn.net/lostrex/article/details/128008714