前言
我们紧接着 上一篇 文章,我们使用账号 jack
和账号 Tom
来分别登录,在上一篇文章测试中可以看到,这两个账号无论哪一个登录,首页页面都会显示 add
页面和 update
页本文来源[email protected]搞@^&代*@码)网9面两个超链接,而对于这两个账号来说,一个拥有访问 add
页面的权限,一个拥有访问 update
页面的权限。那么问题来了,如何才能根据不同用户的身份角色信息来显示不同的页面内容呢?这就要使用 shiro
标签了
thymeleaf
模板引擎使用 shiro
标签
引入依赖
<dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
配置类 ShiroConfig
@Configuration public class ShiroConfig { // 安全管理器 @Bean public DefaultWebSecurityManager getDefaultWebSecurityManager(UserRealm userRealm) { DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); defaultWebSecurityManager.setRealm(userRealm); return defaultWebSecurityManager; } // thymeleaf模板引擎中使用shiro标签时,要用到 @Bean public ShiroDialect getShiroDialect() { return new ShiroDialect(); } @Bean public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager defaultWebSecurityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager); // 设置登录页面url shiroFilterFactoryBean.setLoginUrl("/user/login"); shiroFilterFactoryBean.setSuccessUrl("/user/index"); shiroFilterFactoryBean.setUnauthorizedUrl("/user/unauthorized"); // 注意此处使用的是LinkedHashMap是有顺序的,shiro会按从上到下的顺序匹配验证,匹配了就不再继续验证 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); filterChainDefinitionMap.put("/layer/**", "anon");// 静态资源放行 filterChainDefinitionMap.put("/img/**", "anon"); filterChainDefinitionMap.put("/jquery/**", "anon"); // add.html页面放行 filterChainDefinitionMap.put("/user/add", "authc"); // update.html必须认证 filterChainDefinitionMap.put("/user/update", "authc"); // index.html必须通过认证或者通过记住我登录的,才可以访问 filterChainDefinitionMap.put("/user/index", "user"); // 设置授权,只有user:add权限的才能请求/user/add这个url filterChainDefinitionMap.put("/user/add", "perms[user:add]"); filterChainDefinitionMap.put("/user/update", "perms[user:update]"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } }
index.html
页面
- 首先要引入
shiro
的命名空间:xmlns:shiro=http://www.pollix.at/thymeleaf/shiro
- 使用相应的
shiro
标签
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"> <head> <meta charset="UTF-8"> <title>首页</title> <link rel="shortcut icon" type="image/x-icon" th:href="@{/img/favicon.ico}" rel="external nofollow" /> </head> <body> <h1>首页</h1> <a shiro:hasPermission="'user:add'" th:href="@{/user/add}" rel="external nofollow" >add</a><br> <a shiro:hasPermission="'user:update'" th:href="@{/user/}" rel="external nofollow" >update</a> update <a th:href="@{/user/logout}" rel="external nofollow" >退出登录</a> </body> </html>