SpringSecurity03

操作

基于角色或权限进行访问控制

  1. 通过HttpSecurity对象设置资源的角色要求
        @Override
        protected void configure(AuthenticationManagerBuilder builder) throws Exception {
            
            //临时使用内存版登录模式测试代码
            builder.
                inMemoryAuthentication()   //在内存中完成账号密码检查
                .withUser("tom")   //指定账号
                .password("123123")  //指定密码
                .roles("ADMIN");  //指定当前用户角色
        }
    
         @Override
        protected void configure(HttpSecurity security) throws Exception {
            
            security
                 xxx
                 .andMatchers("xxx")   //针对xxx, 设置访问要求
                 .hasRole("ADMIN")      //具备ADMIN角色才能访问
    
        }    
  2. 只在内存中操作时, SpringSecurity会在角色字符串前面加"ROLE_"前缀
    1. 因为权限和角色会放到同一个集合authorities中, 需要加以区分.
  3. 但从数据库查询得到的用户信息, 角色信息, 权限信息时需要我们手动组装. 手动组装时需要我们自己给角色字符串前加"ROLE_"前缀.

自定义403页面

  1. 简易方案
        @Override
        protected void configure(HttpSecurity security) throws Exception {
            
            security
    xxx .and() .exceptionHandling()
    //指定异常处理器 .accessDeniedPage("xxx") //访问被拒绝时前往的页面 ; }
  2. 定制方案
        @Override
        protected void configure(HttpSecurity security) throws Exception {
            
            security
    xxx .and() .exceptionHandling() .accessDeniedHandler(
    new AccessDeniedHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
    throws IOException, ServletException { request.setAttribute("message", "抱歉, 您无法访问该资源"); request.getRequestDispatcher("/WEB-INF/system-error.jsp").forward(request, response); //跳转到的页面 } }) ; }

使用数据库登录

########

posted @ 2020-04-21 11:27  yellowstreak  阅读(167)  评论(0编辑  收藏  举报