一:資料庫增加權限欄位pperms

二:改變對應的物體類,增加perms
p
ublic class User {
private Integer id;
private String username;
private String password;
private Integer role_id;
private String perms;
三:配置類設定權限過濾器,和未授權訪問頁面
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//設定安全管理器
shiroFilterFactoryBean.setSecurityManager(securityManager);
//添加shiro內置過濾器
Map<String, String> filterMap=new LinkedHashMap<>();
filterMap.put("/test","anon");
filterMap.put("/toLogin","anon");
filterMap.put("/add","perms[user:add]");//授權攔截器
filterMap.put("/update","perms[user:update]");//授權攔截器
filterMap.put("/*","authc");
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");//設定未授權頁面
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactoryBean;
controller,加一段代碼
@RequestMapping("noAuth")
public String noAuth(){
return "noAuth";
}
四:頁面html(即用戶無權訪問當前頁面時跳轉到該頁面)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未授權頁面</title>
</head>
<body>
親,你未經授權訪問該頁面哦
</body>
</html>
五:dao層,根據id查詢介面
public User findById(Integer id);
對應的mapper.xml
<select id="findById" parameterType="int" resultType="com.gzh.springbootshiro.bean.User">
select id,username,password,perms from t_user where id=#{value}
</select>
六:service介面和實作
public User findById(Integer id);
@Override
public User findById(Integer id) {
User user = userMapper.findById(id);
return user;
}
七: realm從資料庫獲取權限資訊,
修改realm
1認證邏輯,回傳的物件,第一個引數為user物件
//執行認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken aro) throws AuthenticationException {
UsernamePasswordToken token=(UsernamePasswordToken ) aro;
User user = userService.fingdByName(token.getUsername());
if (user==null){
return null;
}
return new SimpleAuthenticationInfo(user,user.getPassword(),"");
}
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
//執行授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執行授權邏輯");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Subject subject = SecurityUtils.getSubject();
User user =(User) subject.getPrincipal();
User dbUser = userService.findById(user.getId());
info.addStringPermission(dbUser.getPerms());
return info;
}
八:效果,登錄用戶admin時

添加成功

更新失敗,并跳轉到未授權頁面,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/224193.html
標籤:其他
上一篇:網路安全--數字簽名/數字證書
