1. 程式人生 > >springboot+thymeleaf+shiro標籤

springboot+thymeleaf+shiro標籤

1,pom中加入依賴

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>1.5.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>${thymeleaf.version}</version> </dependency> <!-- shiro安全框架 --> <dependency> <groupId
>
org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> <!--thymeleaf-shiro-extras--> <dependency> <groupId>com.github.theborakompanioni</groupId
>
<artifactId>thymeleaf-extras-shiro</artifactId> <version>1.2.1</version> </dependency>

2,使用者-角色-許可權的表關係

//使用者表
public class User {
    private Integer userId;
    private String userName;
    private Set<Role> roles = new HashSet<>();
}
//角色表
public class User {
    private Integer id;
    private String role;
    private Set<Module> modules = new HashSet<>();
    private Set<User> users = new HashSet<>();
}
//許可權表
public class Module {
    private Integer mid;
    private String mname;
    private Set<Role> roles = new HashSet<>();
}


//使用者查詢
<resultMap id="BaseResultMap" type="com.lanyu.common.model.User" >
    <id column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <!-- 多對多關聯對映:collection -->
    <collection property="roles" ofType="Role">
      <id property="id" column="c_id" />
      <result property="role" column="role" />
      <collection property="modules" ofType="Module">
        <id property="mid" column="mid"/>
        <result property="mname" column="mname"/>
      </collection>
    </collection>
  </resultMap>

//查詢使用者資訊,返回結果會自動分組,得到使用者資訊
  <select id="selectByPhone" resultMap="BaseResultMap" parameterType="java.lang.String" >
    SELECT
      u.*, r.*, m.*
    FROM
        sys_user u
    INNER JOIN sys_user_role ur ON ur.userId = u.user_id
    INNER JOIN sys_role r ON r.rid = ur.roleid
    INNER JOIN sys_role_module mr ON mr.rid = r.rid
    INNER JOIN sys_module m ON mr.mid = m.mid
    WHERE
      u.user_name=#{username} or u.phone=#{username};
  </select>

3,編寫shiro核心類

@Configuration
public class ShiroConfiguration {

    //用於thymeleaf模板使用shiro標籤
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

    @Bean(name="shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        bean.setSecurityManager(manager);
        //配置登入的url和登入成功的url
        bean.setLoginUrl("/loginpage");
        bean.setSuccessUrl("/indexpage");
        //配置訪問許可權
        LinkedHashMap<String, String> filterChainDefinitionMap=new LinkedHashMap<>();
//        filterChainDefinitionMap.put("/loginpage*", "anon"); //表示可以匿名訪問
        filterChainDefinitionMap.put("/admin/*", "authc");//表示需要認證才可以訪問
        filterChainDefinitionMap.put("/logout*","anon");
        filterChainDefinitionMap.put("/img/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/fomts/**","anon");
        filterChainDefinitionMap.put("/**", "anon");
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return bean;
    }
    //配置核心安全事務管理器
    @Bean(name="securityManager")
    public SecurityManager securityManager(@Qualifier("authRealm") AuthRealm authRealm) {
        System.err.println("--------------shiro已經載入----------------");
        DefaultWebSecurityManager manager=new DefaultWebSecurityManager();
        manager.setRealm(authRealm);
        return manager;
    }
    //配置自定義的許可權登入器
    @Bean(name="authRealm")
    public AuthRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {
        AuthRealm authRealm=new AuthRealm();
        authRealm.setCredentialsMatcher(matcher);
        return authRealm;
    }
    //配置自定義的密碼比較器
    @Bean(name="credentialsMatcher")
    public CredentialsMatcher credentialsMatcher() {
        return new CredentialsMatcher();
    }
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator creator=new DefaultAdvisorAutoProxyCreator();
        creator.setProxyTargetClass(true);
        return creator;
    }
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {
        AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(manager);
        return advisor;
    }
}

— - - -- - -- - -- - -- - - -- - - - -- 
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    //認證.登入
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//獲取使用者輸入的token
        String username = utoken.getUsername();
        User user = userService.selectByPhone(username);
        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());//放入shiro.呼叫CredentialsMatcher檢驗密碼
    }
    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        User user=(User) principal.fromRealm(this.getClass().getName()).iterator().next();//獲取session中的使用者
        List<String> permissions=new ArrayList<>();
        Set<Role> roles = user.getRoleList();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        List<String> listrole = new ArrayList<>();
        if(roles.size()>0) {
            for(Role role : roles) {
                if(!listrole.contains(role.getRole())){
                    listrole.add(role.getRole());
                }
                Set<Module> modules = role.getModules();
                if(modules.size()>0) {
                    for(Module module : modules) {
                        permissions.add(module.getMname());
                    }
                }
            }
        }
        info.addRoles(listrole);                       //將角色放入shiro中.
    info.addStringPermissions(permissions);         //將許可權放入shiro中.
        return info;
    }

}


//自定義密碼比較器
public class CredentialsMatcher extends SimpleCredentialsMatcher {

    private  Logger logger = Logger.getLogger(CredentialsMatcher.class);

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;
        //所需加密的引數  即  使用者輸入的密碼
        String source = String.valueOf(utoken.getPassword());
        //[鹽] 一般為使用者名稱 或 隨機數
        String salt = utoken.getUsername();
        //加密次數
        int hashIterations = 50;
        SimpleHash sh = new SimpleHash("md5", source, salt, hashIterations);
        String Strsh =sh.toHex();
        //列印最終結果
        logger.info("正確密碼為:"+Strsh);
        //獲得資料庫中的密碼
        String dbPassword= (String) getCredentials(info);
        logger.info("資料庫密碼為:"+dbPassword);
        //進行密碼的比對
        return this.equals(Strsh, dbPassword);
    }

}

4,登入控制器

    @RequestMapping("/loginUser")
    public String loginUser(String username,String password,HttpSession session) {
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        Map map=new HashMap();
        try {
            subject.login(usernamePasswordToken);   //完成登入
            User user=(User) subject.getPrincipal();
            session.setAttribute("user", user);
            return "index";
        } catch (IncorrectCredentialsException e) {
            map.put("msg", "密碼錯誤");
        } catch (LockedAccountException e) {
            map.put("msg", "登入失敗,該使用者已被凍結");
        } catch (AuthenticationException e) {
            map.put("msg", "該使用者不存在");
        } catch (Exception e) {
            return "login";//返回登入頁面
        }
        return map.toString();
    }

5,thymeleaf頁面許可權控制

<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

//最為屬性控制
<button  type="button" shiro:authenticated="true" class="btn btn-outline btn-default">
    <i class="glyphicon glyphicon-plus" aria-hidden="true"></i>
</button>
//作為標籤
<shiro:hasRole name="admin">
    <button type="button" class="btn btn-outline btn-default">
        <i class="glyphicon glyphicon-heart" aria-hidden="true"></i>
    </button>
</shiro:hasRole>

6,標籤說明

guest標籤
  <shiro:guest>
  </shiro:guest>
  使用者沒有身份驗證時顯示相應資訊,即遊客訪問資訊。

user標籤
  <shiro:user>  
  </shiro:user>
  使用者已經身份驗證/記住我登入後顯示相應的資訊。

authenticated標籤
  <shiro:authenticated>  
  </shiro:authenticated>
  使用者已經身份驗證通過,即Subject.login登入成功,不是記住我登入的。

notAuthenticated標籤
  <shiro:notAuthenticated>
  
  </shiro:notAuthenticated>
  使用者已經身份驗證通過,即沒有呼叫Subject.login進行登入,包括記住我自動登入的也屬於未進行身份驗證。

principal標籤
  <shiro: principal/>
  
  <shiro:principal property="username"/>
  相當於((User)Subject.getPrincipals()).getUsername()。

lacksPermission標籤
  <shiro:lacksPermission name="org:create">
 
  </shiro:lacksPermission>
  如果當前Subject沒有許可權將顯示body體內容。

hasRole標籤
  <shiro:hasRole name="admin">  
  </shiro:hasRole>
  如果當前Subject有角色將顯示body體內容。

hasAnyRoles標籤
  <shiro:hasAnyRoles name="admin,user">
   
  </shiro:hasAnyRoles>
  如果當前Subject有任意一個角色(或的關係)將顯示body體內容。

lacksRole標籤
  <shiro:lacksRole name="abc">  
  </shiro:lacksRole>
  如果當前Subject沒有角色將顯示body體內容。

hasPermission標籤
  <shiro:hasPermission name="user:create">  
  </shiro:hasPermission>
  如果當前Subject有許可權將顯示body體內容