springboot-shiro-thymeleaf简单运用

springboot-shiro

  • 依赖

    • <!--shiro-->
      <dependency>
          <groupId>com.github.boyazuo</groupId>
          <artifactId>shiro-spring-boot-starter</artifactId>
          <version>1.0.3</version>
      </dependency>
       <!--thymeleaf-shiro-->
      <dependency>
      	<groupId>com.github.theborakompanioni</groupId>
      	<artifactId>thymeleaf-extras-shiro</artifactId>
      	<version>2.0.0</version>
      </dependency>
      
  • 配置类:ShiroConfig

    • /*shiro命名空间*/
      @Bean
      public ShiroDialect getShiroDialect(){
      	return new ShiroDialect();
      }
      
      @Bean
      /*First:创建自定义Realm*/
      public UserRealm userRealm(){
      	return new UserRealm();
      }
      
      @Bean(name = "defaultWebSecurityManager")
      /*创建安全管理器SecuritManage
      * 1. 添加realm
      * */
      public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
      
      	DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
          
      	securityManager.setRealm(userRealm);
          
      	return securityManager;
      }
      
      @Bean
      /*创建工厂SecurityManagerFactory
      * 1. 设置安全管理器
      * 2. 设置网页权限
      * 3. 设置登录页面
      * 4. 设置登出
      * */
      public ShiroFilterFactoryBean getShiroFilterFactoryBean(
      @Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager securityManager){
      
              ShiroFilterFactoryBean shiroFactory = new ShiroFilterFactoryBean();
      
              shiroFactory.setSecurityManager(securityManager);
      
              /* 设置网页权限
              * anon 无需认证就可以访问
              * authc 需认证才可访问
              * user 必需拥有  记住我  功能才可访问
              * perms 拥有对某个资源的权限才可访问
              * role 拥有某个角色权限才可访问
              * */
      
              Map<String,String> filterMap =new LinkedHashMap<>();
      
              filterMap.put("/level1","perms[user:level1]");
              filterMap.put("/level2","perms[user:level2]");
              filterMap.put("/level3","perms[user:level3]");
      
              shiroFactory.setFilterChainDefinitionMap(filterMap);
      
              shiroFactory.setLoginUrl("/login");
      
              return shiroFactory;
          }
      
  • 引入命名空间:xmlns:shiro=“http://www.pollix.at/thymeleaf/shiro”

  • html基础语法

    • <p shiro:guest>Please <a th:href="@{login}">登录</a></p>>
          
      <h1 shiro:principal property="username"></h1>
          
      <div shiro:hasPermission="user:level1">
      	<a href="level1">等级一</a>
      </div>
          
      <div shiro:hasRole="user">
      	<h1 shiro:principal property="username"></h1>
      </div>
      
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页