Shiro结合配置文件实战实现权限验证

一.shiro.ini文件的了解

shiro配置文件

一般在真实项目中其实这种配置文件不怎么常用,shiro一般都是结合spring一起使用,不过还是可以简单的了解一下

#用户
#写法 用户名=密码,角色名1,角色名2
[users]
user1=123456,role1
user2=123456,role2
user3=123456,role3
#角色
#写法:role1=权限名1,权限名2 
[roles]
role1=user:add,user:query,user:delete.user:update
role2=user:add,user:query
role3=user:delete.user:update

#Url控制
[urls]
#url地址=内置filter或自定义filter
# 访问时出现/login的url必须去认证.支持authc对应的Filter 
/login=authc
# 任意的url都不需要进行认证等功能.
/** = anon
# 所有的内容都必须保证用户已经登录.
/**=user
# url abc 访问时必须保证用户具有role1和role2角色.
/abc=roles[“role1,role2”]
#用户退出的
/user/logout=logout


二.使用shiro.ini文件进行shiro的权限验证

运行环境

导入shiro的核心包以及配置文件

      <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-core</artifactId>
          <version>1.4.1</version>
      </dependency>

创建自定义realm

public class UserRealm extends AuthorizingRealm {
    UserService userService = new UserImpl();
    RoleService roleService = new RoleServieImpl();
    PermissionService permissionService = new PermissionServiceImpl();

    //验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //得到用户名
        String username = token.getPrincipal().toString();
        String password = token.getCredentials().toString();
        User user = userService.queryUserName(username);
        List<String> permission = permissionService.queryPermissionByUserName(username);
        List<String> role = roleService.queryRoleByUserName(username);
        ActiveUser activeUser = new ActiveUser(role, permission, user);
        //数据库里查询是否有对应的用户
        //然后才会进行认证  不是用户名密码一起认证

        //如果用户存在
        if (user != null){

            /**
             * 参数1:传任意对象 可以传参给授权方法
             * 参数2:传数据库查出来的密码
             * 参数3:当前类名
             */
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser, user.getPassword(), this.getName());

            //根据用户名得到方法
            return info;
        }else {
            return null;
        }

    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ActiveUser activeUser = (ActiveUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(activeUser.getRoles());
       info.addStringPermissions(activeUser.getPermission());

        System.out.println("授权");

        return  info;
    }
}

测试

public class TestRealm {
    private static final transient Logger log = LoggerFactory.getLogger(TestAuthentication.class);
    public static void main(String[] args) {
        String username= "user1";
        String password = "123456";
        //创建安全管理器工厂对象
        IniSecurityManagerFactory managerFactory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //创建安全管理器实例
        DefaultSecurityManager securityManager = (DefaultSecurityManager)managerFactory.getInstance();
        //绑定安全管理器到当前线程
        SecurityUtils.setSecurityManager(securityManager);
        //得到realm对象 再认证就会走这里
        UserRealm userRealm = new UserRealm();
        securityManager.setRealm(userRealm);
        //得到主体对象
        Subject subject = SecurityUtils.getSubject();
        //封装认证
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        try {
            //进行认证
            subject.login(token);
            System.out.println("登录成功");

            //判断是否有该角色
            boolean role1 = subject.hasRole("role1");
            System.out.println(role1);

            //判断是否有对应的权限
            boolean permitted = subject.isPermitted("user:add");
            System.out.println(permitted);
        }catch (AuthenticationException e){
            System.out.println("用户名或密码错误");
        }


    }
}
原文地址:https://www.cnblogs.com/blackmlik/p/12766513.html