搭建环境见: 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
均可以访问了