zoukankan      html  css  js  c++  java
  • 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); //跳转到的页面 } }) ; }

    使用数据库登录

    ########

  • 相关阅读:
    大道至简第五章读后感
    课后作业1:字串加密
    String类中的equals()方法:
    构架之美读后感5
    构架之美读后感4
    构架之美读后感3
    构架之美读后感2
    构架之美读后感1
    关于联想y485p装win10显卡驱动问题
    软件需求与分析课堂讨论一
  • 原文地址:https://www.cnblogs.com/binwenhome/p/12743337.html
Copyright © 2011-2022 走看看