Shiro的角色管理,可以根據
添加Role實體類,修改User類,修改數據源
@Getter @Setter @AllArgsConstructor public class Role implements Serializable { private String name; }
@Getter @Setter public class User implements Serializable { private String id; private String username; private String password; private String salt; private Set<Role> roles; public User(String username, String password) { this.id = UUID.randomUUID().toString().replace("-", ""); this.username = username; this.salt = getId().substring(0, 6); this.password = new Sha512Hash(password, getSalt()).toString(); this.roles = new HashSet<>(); } }
static { userMap.put("user", new User("user", "123456")); userMap.put("admin", new User("admin", "123456")); Role userRole = new Role("user"); Role adminRole = new Role("admin"); userMap.get("user").getRoles().add(userRole); userMap.get("admin").getRoles().add(userRole); userMap.get("admin").getRoles().add(adminRole); }
增加、修改頁面用於測試功能
<!—403.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>403</title> </head> <body> 沒有權限 <a href="/index">返回首頁</a> </body> </html>
<!—admin.html--> <!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>管理界面</title> </head> <body> <p th:text="${user.username}+' 管理員您好'"></p> <a href="/index">返回首頁</a> </body> </html>
<!—index.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>welcome</title> </head> <body> 歡迎登錄網頁 <a href="/user">個人主頁</a> <a href="/admin">用戶管理</a> <a href="/logout">退出登錄</a> </body> </html>
<!—user.html--> <!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>個人頁面</title> </head> <body> <p th:text="${user.username}+' 用戶您好'"></p> <a href="/index">返回首頁</a> </body> </html>
修改Controller
@RequestMapping(value = {"/user"}, method = RequestMethod.GET)
public String user(Model model) {
User user = (User) ShiroUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "user";
}
@RequestMapping(value = {"/admin"}, method = RequestMethod.GET)
public String admin(Model model) {
User user = (User) ShiroUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "admin";
}
@RequestMapping(value = {"/403"}, method = RequestMethod.GET)
public String noAuth(Model model) {
return "403";
}
在MyRealm的doGetAuthorizationInfo 中將用戶的角色配置到AuthorizationInfo 中返回
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); User user = (User) principalCollection.getPrimaryPrincipal(); for (Role role : user.getRoles()) { info.addRole(role.getName()); } return info; }
修改Shiro攔截器配置
//角色攔截 filterChainDefinitionMap.put("/user", "authc,roles[user]"); filterChainDefinitionMap.put("/admin", "authc,roles[user,admin]"); //未授權界面; shiroFilterFactoryBean.setUnauthorizedUrl("/403");
分別登錄使用user、admin用戶訪問/admin 和/user 可以發現user 沒有權限訪問/admin
