搭建環境見: SpringBoot整合Shiro 一:搭建環境html
shiro配置類見: SpringBoot整合Shiro 二:Shiro配置類數據庫
shiro整合Mybatis見:SpringBoot整合Shiro 三:整合Mybatisapp
若是用戶沒有擁有 user:add 就沒法訪問add頁面ide
filterMap.put("/user/add","perms[user:add]");post
若是用戶沒有擁有 user:update 就沒法訪問 update 頁面測試
filterMap.put("/user/update","perms[user:update]");url
跳轉到一個未受權的頁面spa
bean.setUnauthorizedUrl("/noauth");3d
@Bean(name = "shiroFilterFactoryBean") public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){ ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean(); bean.setSecurityManager(defaultWebSecurityManager); Map<String ,String> filterMap = new LinkedHashMap<>(); //受權 filterMap.put("/user/add","perms[user:add]"); filterMap.put("/user/update","perms[user:update]"); filterMap.put("/user/*","authc"); bean.setFilterChainDefinitionMap(filterMap); //未受權頁面 bean.setUnauthorizedUrl("/noauth"); bean.setLoginUrl("/toLogin"); return bean; }
使用 @ResponseBody 直接顯示字符串code
@RequestMapping("/noauth") @ResponseBody public String unauthorized(){ return "未受權沒法訪問"; }
登陸root用戶,開始訪問2個頁面
add
update
添加 perms(varchar)
使用了Lombok
package com.zy.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String pwd; private String perms; }
UserRealm 中 AuthorizationInfo(受權)
受權的對象 SimpleAuthorizationInfo
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
添加權限的方法 addStringPermission
info.addStringPermission("user:add");
拿到當前登陸的對象(認證成功以後,能夠獲取到)
Subject subject = SecurityUtils.getSubject();
獲取到User
User currentUser = (User) subject.getPrincipal();
設置當前用戶的權限
info.addStringPermission(currentUser.getPerms());
//受權 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("執行了=>受權doGetAuthorizationInfo"); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.addStringPermission("user:add"); //拿到當前登陸的對象 Subject subject = SecurityUtils.getSubject(); //獲取到User User currentUser = (User) subject.getPrincipal(); //設置當前用戶的權限 info.addStringPermission(currentUser.getPerms()); return info; }
能夠訪問add頁面了,由於被受權了
update仍然不行,由於沒有權限
能夠訪問add頁面
update不行
add
update
均可以訪問了