springboot整合shiro(授权)

一:数据库增加权限字段perms
在这里插入图片描述

二:改变对应的实体类,增加perms

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";
    }

四:页面noAuth.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(),"");
}

2 授权逻辑

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时
springboot整合shiro(授权)_第1张图片

添加成功
springboot整合shiro(授权)_第2张图片
更新失败,并跳转到未授权页面。
springboot整合shiro(授权)_第3张图片

你可能感兴趣的:(shiro,spring,java)