Shiro入门

》#千锋逆战#
要添加的依赖
pom.xml


        
        
            org.apache.shiro
            shiro-core
            1.4.0
        
        
            commons-logging
            commons-logging
            1.2
        

        
            junit
            junit
            4.12
        
    

写一个ini文件
shiro.ini

[users]
zhangsan=123,admin, guest
lisi=456,guest
[roles]
admin=select, save, update, delete
guest=select, update

测试

public static void main(String[] args) {
        // 构建SecurityManager工厂,IniSecurityManagerFactory可以从ini文件中初始化SecurityManager环境
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory();

        // 通过工厂创建SecurityManager
        SecurityManager manager = factory.getInstance();

        // 将SecurityManager设置到运行环境中
        SecurityUtils.setSecurityManager(manager);

        //创建一个Subject实例,该实例认证需要使用上面创建的SecurityManager
        Subject subject = SecurityUtils.getSubject();

        Scanner input = new Scanner(System.in);

        System.out.println("请输入用户名:");
        String username = input.next();
        System.out.println("请输入密码:");
        String password = input.next();

        //创建token令牌,账号和密码是ini文件中配置的
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            //用户登录
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("未知账户");
            e.printStackTrace();
        } catch (CredentialsException e) {
            System.out.println("密码错误");
            e.printStackTrace();
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        System.out.println("success.");

        System.out.println(subject.hasRole("admin"));
        System.out.println(subject.hasRole("guest"));

        List roles = Arrays.asList("admin", "guest");
        System.out.println(Arrays.toString(subject.hasRoles(roles)));

        System.out.println("---------");

        System.out.println(subject.isPermitted("select"));
        System.out.println(subject.isPermitted("save"));

        //List primitts = Arrays.asList("select", "update");
        System.out.println(Arrays.toString(subject.isPermitted("select", "update", "save")));
    }

你可能感兴趣的:(Shiro入门)