• 【SpringSecurity】SpringSecurity2.7.x 的使用(02)


    5. 获取认证后用户的信息

    获取登录后用户的信息: SpringSecurity默认会把认证成功的用户信息保存到SrcurityContext,类似于session会话。 我们要想获取认证用户信息,可以在SrcurityContext该类拿到。

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        /**
         * 认证成功后,SpringSecurity会把用户的信息封装到Authentication该类中,
         * 并且该类存放在SecurityContext对象中---等价于session
         * @return Authentication
         */
        @GetMapping("/info")
        public Authentication authentication() {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            Authentication authentication = securityContext.getAuthentication();
            //通过Authentication通常可以拿到Principal,里面存放着用户信息
            //Object principal = authentication.getPrincipal();
            //System.out.println(principal);
            return authentication;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

    用户赋予权限之后,就不会显示角色信息。
    在这里插入图片描述

    6. 设置登录成功和失败的路径

    如果未指定登录成功的路径,则默认跳转到 / 路径。如果未指定登录失败的路径,则默认跳转到登录页面(后面会多个?error参数)
    在这里插入图片描述

    1. 注意不能直接跳转到静态资源路径,要先跳到controller中转一下
    2. 不常用的用法,现在讲究前后端分离,一般是无论登录成功与否只往前端发送json数据,而不再是跳转到某个页面。

    7. 设置登录成功和登录失败时返回json数据

      //认证
      http
              .formLogin()
              //默认登录页面
              .loginPage("/login.html")
              //登录的处理路径,无需自己创建该路径的业务处理功能。
              .loginProcessingUrl("/login")
              //登录成功返回json
              .successHandler((request, response, authentication) -> {
                  response.setContentType("application/json;charset=utf-8");
                  PrintWriter writer = response.getWriter();
                  Map<String, Object> map = new HashMap<>();
                  map.put("code", 200);
                  map.put("msg", "登录成功");
                  map.put("data", "哈哈哈哈哈");
                  String jsonStr = JSONUtil.toJsonStr(map);
                  writer.println(jsonStr);
              })
              //登录失败返回json
              .failureHandler((request, response, authentication) -> {
                  response.setContentType("application/json;charset=utf-8");
                  PrintWriter writer = response.getWriter();
                  Map<String, Object> map = new HashMap<>();
                  map.put("code", 500);
                  map.put("msg", "登录失败");
                  map.put("data", "呵呵呵呵呵");
                  String jsonStr = JSONUtil.toJsonStr(map);
                  writer.println(jsonStr);
              })
              //放行
              .permitAll();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    以上是关于SpringSecurity的认证

    二、SpringSecurity授权

    1. 配置文件中授权

    认证成功后,当前用户具有哪个权限才可以访问对应的资源。

    admin---->user:query, user:delete, user:insert,user:update

    user------>user:query , user:export

    1. 创建资源类—控制层类。
    @GetMapping("/user/query")
    @ResponseBody
    public String query(){
        return "user::query";
    }
    
    @GetMapping("/user/delete")
    @ResponseBody
    public String delete(){
        return "user::delete";
    }
    
    @GetMapping("/user/update")
    @ResponseBody
    public String update(){
        return "user::update";
    }
    
    @GetMapping("/user/insert")
    @ResponseBody
    public String insert(){
        return "user::insert";
    }
    
    @GetMapping("/user/export")
    @ResponseBody
    public String export(){
        return "user::query";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    1. 修改security配置
      在这里插入图片描述

    默认登录成功后访问相应的资源,如果有该权限,则返回对应资源返回的结果,如果没有权限返回一个403错误页面。
    在这里插入图片描述

    非常不友好,前后分离,应该返回一个json数据。

    //权限不足时返回json数据
    http.exceptionHandling().accessDeniedHandler((request, response, accessDeniedException) -> {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 403);
        map.put("msg", "您没有权限访问");
        map.put("data", "呵呵呵呵呵");
        String jsonStr = JSONUtil.toJsonStr(map);
        writer.println(jsonStr);
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2. 方法级别的授权

    配置文件中授权,我们需要一一对资源和权限进行绑定,如果后期资源非常多,那么这里的代码就比较麻烦。 我们可以使用在方法上添加注解完成相应的绑定。

    1. 把原来的代码注掉
      在这里插入图片描述
    2. 开启注解驱动

    在配置文件中添加注解驱动
    在这里插入图片描述

    1. 使用注解在相应资源上
      在这里插入图片描述

    通过权限授权

    • hasAuthority :有这个权限可以访问,只能写一个权限
    • hasAnyAuthority :为如果有其中的任意一个权限,就可以访问,里面可以写多个权限,例如:@PreAuthorize("hasAnyAuthority('user:query','user:delete')")

    通过角色授权

    • hasAnyRole :有里面任意一个角色,就可以访问
    • hasRole :有这个角色就可以访问
  • 相关阅读:
    vue 项目在加载完成之前,显示预置加载动画
    10 关联模型《ThinkPHP6 入门到电商实战》
    基于Internet应用的分销ERP系统源码
    【TcaplusDB知识库】WebClient用户如何读取和修改数据
    Android系统启动流程
    Google身份验证器Google Authenticator的java服务端实现
    智能护栏碰撞监测系统:强化道路安全的智能守卫
    阿里云服务器u1和经济型e实例有什么区别?
    请求合并与拆分在并发场景中应用
    ensp配置浏览器访问USG6000V1防火墙
  • 原文地址:https://blog.csdn.net/qq_60969145/article/details/127630924