spring boot整合shiro(授权)

一:数据库增加权限字段pperms
spring boot整合shiro(授权)文章插图
二:改变对应的实体类,增加permsp
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 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(即用户无权访问当前页面时跳转到该页面)
【spring boot整合shiro(授权)】未授权页面亲 , 你未经授权访问该页面哦五:dao层 , 根据id查询接口
public User findById(Integer id);对应的mapper.xml
select id,username,password,perms from t_user where id=#{value}六:service接口和实现
public User findById(Integer id);@Overridepublic User findById(Integer id) {User user = userMapper.findById(id);return user;}七: realm从数据库获取权限信息 , 修改realm1认证逻辑 , 返回的对象 , 第一个参数为user对象
//执行认证@Overrideprotected 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 {@Autowiredprivate UserService userService;//执行授权@Overrideprotected 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时
spring boot整合shiro(授权)文章插图
添加成功
spring boot整合shiro(授权)文章插图
更新失败 , 并跳转到未授权页面 。
spring boot整合shiro(授权)文章插图
版权声明:本文为博主原创文章 , 遵循 CC 4.0 BY-SA 版权协议 , 转载请附上原文出处链接和本声明 。
本文链接: