Shiro

使用默认iniRealm登陆

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.3</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>1.2.2</version>
    </dependency>
  </dependencies>

shiro.ini

[users]
#模拟数据库中的用户数据:用户=密码
zs=zhangsan
ls=lisi

登陆

//使用默认iniRealm登陆
    @Test
    public void testLogin() throws Exception {
        //1.创建securityManager工厂对象
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro.ini");

        //2.通过工厂对象创建SecurityManager对象
        SecurityManager securityManager = factory.getInstance();

        //3.通过SecurityUtils将securityManager绑定到当前运行环境中,让系统能够随时随地访问securityManager对象
        SecurityUtils.setSecurityManager(securityManager);

        //4.通过SecurityUtils获取当前登陆主体Subject 注意:此时的主体没有经过认证
        Subject subject = SecurityUtils.getSubject();

        //5.收集主体登陆的凭证信息,即账号密码
        UsernamePasswordToken token = new UsernamePasswordToken("zs", "zhangsan");

        //6.主体登陆
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("无此账户");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        //7.验证主体是否登陆成功
        System.out.println("验证主体登陆是否成功:" + subject.isAuthenticated());

        //8.登出
        subject.logout();
        System.out.println("验证主体登陆是否成功:" + subject.isAuthenticated());
    }

使用自定义Realm登陆

shiro-realm.ini

#自定义Realm
myRealm= com.c.MyRealm
#指定SecurityManager的realms实现
securityManager.realms=$myRealm

com.c.MyRealm

package com.c;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyRealm extends AuthorizingRealm {

    //在一个项目中可能会存在多个Realm,重写此方法以便区分
    @Override
    public String getName() {
        return "MyRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //通过用户名去数据库中寻找记录并将其封装为AuthenticationInfo返回给认证器进行信息校验

        //获取token中的用户名
        String username = (String) token.getPrincipal();
        //根据用户名去数据库中查询数据
        if (!"zs".equals(username)) {
            return null;
        }
        //假设数据库中的真实密码
        String password = "zhangsan";

        AuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
        return info;
    }
}

登陆

//使用自定义Realm登陆
    @Test
    public void testLoginByMyRealm() throws Exception {
        //1.创建securityManager工厂对象
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro-realm.ini");

        //2.通过工厂对象创建SecurityManager对象
        SecurityManager securityManager = factory.getInstance();

        //3.通过SecurityUtils将securityManager绑定到当前运行环境中,让系统能够随时随地访问securityManager对象
        SecurityUtils.setSecurityManager(securityManager);

        //4.通过SecurityUtils获取当前登陆主体Subject 注意:此时的主体没有经过认证
        Subject subject = SecurityUtils.getSubject();

        //5.收集主体登陆的凭证信息,即账号密码
        UsernamePasswordToken token = new UsernamePasswordToken("zs", "zhangsan");

        //6.主体登陆
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("无此账户");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        //7.验证主体是否登陆成功
        System.out.println("验证主体登陆是否成功:" + subject.isAuthenticated());

        //8.登出
        subject.logout();
        System.out.println("验证主体登陆是否成功:" + subject.isAuthenticated());
    }

shiro加密登陆

shiro-cryptography.ini

[main]
#定义凭证匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法,shiro支持md5和sha
credentialsMatcher.hashAlgorithmName=md5
#散列次数
credentialsMatcher.hashIterations=3

#将凭证匹配器设置到realm
passwordRealm=com.c.PasswordRealm
passwordRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$passwordRealm

com.c.PasswordRealm

package com.c;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class PasswordRealm extends AuthorizingRealm {

    //在一个项目中可能会存在多个Realm,重写此方法以便区分
    @Override
    public String getName() {
        return "PasswordRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //通过用户名去数据库中寻找记录并将其封装为AuthenticationInfo返回给认证器进行信息校验

        //获取token中的用户名
        String username = (String) token.getPrincipal();
        //根据用户名去数据库中查询数据
        if (!"zs".equals(username)) {
            return null;
        }
        //假设数据库中的真实密码,此处为密文 加密方式: 密码 + 盐(用户名) + 散列次数3
        String password = "596e98f8185153cad8c459d870913dc1";

        //参数3:盐
        AuthenticationInfo info = new SimpleAuthenticationInfo(username, password,
                ByteSource.Util.bytes(username), getName());
        return info;
    }
}

加密登陆

 //使用加密Realm登陆
    @Test
    public void testLoginByPasswordRealm() throws Exception {
        //1.创建securityManager工厂对象
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro-cryptography.ini");

        //2.通过工厂对象创建SecurityManager对象
        SecurityManager securityManager = factory.getInstance();

        //3.通过SecurityUtils将securityManager绑定到当前运行环境中,让系统能够随时随地访问securityManager对象
        SecurityUtils.setSecurityManager(securityManager);

        //4.通过SecurityUtils获取当前登陆主体Subject 注意:此时的主体没有经过认证
        Subject subject = SecurityUtils.getSubject();

        //5.收集主体登陆的凭证信息,即账号密码
        UsernamePasswordToken token = new UsernamePasswordToken("zs", "zhangsan");

        //6.主体登陆
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("无此账户");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        //7.验证主体是否登陆成功
        System.out.println("验证主体登陆是否成功:" + subject.isAuthenticated());

        //8.登出
        subject.logout();
        System.out.println("验证主体登陆是否成功:" + subject.isAuthenticated());
    }

检查用户是否拥有角色

shiro-role.ini

[users]
#模拟数据库中的用户数据:用户=密码,角色1,角色2...
zs=zhangsan,role1,role2
ls=lisi,role3

[roles]
role1=user:create,user:update
role2=user:create,user:delete
role3=user:create

检查

//检查用户是否拥有角色
    @Test
    public void testRole() throws Exception {
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro-role.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zs", "zhangsan");
        subject.login(token);


        System.out.println("是否拥有role1:" + subject.hasRole("role1"));
        System.out.println("是否同时拥有role1、role2:" + subject.hasAllRoles(Arrays.asList("role1", "role2")));
        System.out.println("是否同时拥有role1、role2、role3:"
                + subject.hasAllRoles(Arrays.asList("role1", "role2", "role3")));
        System.out.println("拥有role1、role2、role3情况:"
                + Arrays.toString(subject.hasRoles(Arrays.asList("role1", "role2", "role3"))));
        System.out.println();

        try {
            subject.checkRole("role1");
            System.out.println("1");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            subject.checkRole("role3");
            System.out.println("2");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            subject.checkRoles("role1", "role2");
            System.out.println("3");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            subject.checkRoles("role1", "role2", "role3");
            System.out.println("4");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            subject.checkRoles(Arrays.asList("role1", "role2"));
            System.out.println("5");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            subject.checkRoles(Arrays.asList("role1", "role2", "role3"));
            System.out.println("6");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }


    }

检查权限

//检查用户是否拥有权限
    @Test
    public void testPerm() throws Exception {
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro-role.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zs", "zhangsan");
        subject.login(token);


        System.out.println("是否拥有权限user:create:" + subject.isPermitted("user:create"));
        System.out.println("是否拥有权限user:list:" + subject.isPermitted("user:list"));
        System.out.println("拥有权限user:create、user:update的情况:"
                + Arrays.toString(subject.isPermitted("user:create", "user:update")));
        System.out.println("拥有权限user:create、user:update、user:list的情况:"
                + Arrays.toString(subject.isPermitted("user:create", "user:update", "user:list")));
        System.out.println("是否同时拥有权限user:create、user:update:"
                + subject.isPermittedAll("user:create", "user:update"));
        System.out.println("是否同时拥有权限user:create、user:list:"
                + subject.isPermittedAll("user:create", "user:list"));

        System.out.println();

        try {
            subject.checkPermission("user:create");
            System.out.println("1");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            subject.checkPermission("user:list");
            System.out.println("2");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            subject.checkPermissions("user:create", "user:update");
            System.out.println("3");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            subject.checkPermissions("user:delete", "user:list");
            System.out.println("4");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

自定义realm检查用户拥有权限

shiro-permission.ini

[main]
#定义凭证匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法,shiro支持md5和sha
credentialsMatcher.hashAlgorithmName=md5
#散列次数
credentialsMatcher.hashIterations=3

#将凭证匹配器设置到realm
passwordRealm=com.c.PermissionRealm
passwordRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$passwordRealm
PermissionRealm
package com.c;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

public class PermissionRealm extends AuthorizingRealm {

    //在一个项目中可能会存在多个Realm,重写此方法以便区分
    @Override
    public String getName() {
        return "PermissionRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //principals封装了AuthenticationInfo的用户名信息
        String username = (String) principals.getPrimaryPrincipal();

        //模拟数据库数据
        List<String> roles = new ArrayList<String>();
        List<String> permissions = new ArrayList<String>();

        roles.add("role1");
        permissions.add("user:create");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //通过用户名去数据库中寻找记录并将其封装为AuthenticationInfo返回给认证器进行信息校验

        //获取token中的用户名
        String username = (String) token.getPrincipal();
        //根据用户名去数据库中查询数据
        if (!"zs".equals(username)) {
            return null;
        }
        //假设数据库中的真实密码,此处为密文 加密方式: 密码 + 盐(用户名) + 散列次数3
        String password = "596e98f8185153cad8c459d870913dc1";

        //参数3:盐
        AuthenticationInfo info = new SimpleAuthenticationInfo(username, password,
                ByteSource.Util.bytes(username), getName());
        return info;
    }
}

Test

 //自定义授权
    @Test
    public void testByMyPerm() throws Exception {
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro-permission.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zs", "zhangsan");
        subject.login(token);


        System.out.println("是否拥有权限user:create:" + subject.isPermitted("user:create"));
        System.out.println("是否拥有权限user:list:" + subject.isPermitted("user:list"));
        System.out.println("是否拥有角色role1:" + subject.hasRole("role1"));
        System.out.println("是否拥有角色role2:" + subject.hasRole("role2"));
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值