nullcy 2020-04-30
搭建环境见: SpringBoot整合Shiro 一:搭建环境
shiro配置类见: SpringBoot整合Shiro 二:Shiro配置类
shiro整合Mybatis见:SpringBoot整合Shiro 三:整合Mybatis
如果用户没有拥有 user:add 就无法访问add页面
filterMap.put("/user/add","perms[user:add]");
如果用户没有拥有 user:update 就无法访问 update 页面
filterMap.put("/user/update","perms[user:update]");
跳转到一个未授权的页面
bean.setUnauthorizedUrl("/noauth");
@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 直接显示字符串
@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

都可以访问了