Shiro权限框架

  • 2019 年 10 月 3 日
  • 笔记

1.Shiro???

??Shiro????????????????????????????????????????????????????????

2.???????Shiro

?????RBAC?Role Based Access Control???????????????????????????Shiro????????????????Shiro???RBAC???????????
??????????HTML???????????????????Shiro???????

3.Shiro???

??shiro??????http://shiro.apache.org/download.html

??Shiro???

??????????????????jar???

? ? Maven ?? ? ?
 shiro-all  ?????  ??Shiro????? 
 shiro-core
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
 ????shiro??????????slf4j ? commons-beanutils ???????INI????
 shiro-web  <dependency>

<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
 ????Web???
 shiro-aspectj  <dependency>

<groupId>org.apache.shiro</groupId>
<artifactId>shiro-aspectj</artifactId>
<version>1.3.2</version>
</dependency>
 AspectJ?Shiro AOP??????
 shiro-cas

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-cas</artifactId>
<version>1.3.2</version>
</dependency>

 ?cas?????????
 shiro-ehcache

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.3.2</version>
</dependency>

 ?echche???????
 shiro-hazelcast

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-hazelcast</artifactId>
<version>1.3.2</version>
</dependency>

 ?hazelcast?famework?????
 shiro-features
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-features</artifactId>
<version>1.3.2</version>
</dependency>
 Karaf ???
 shiro-guice

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-guice</artifactId>
<version>1.3.2</version>
</dependency>

 ????guice????????spring?ioc???
 shiro-quartz

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-quartz</artifactId>
<version>1.3.2</version>
</dependency>

 ?quartz???????????
 shiro-spring
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
 ??Spring?????

????????????????

4.Shiro???

??

Authentication?????????????????????
Authorization???????????????????
Session Management?????????????????
Cryptography????????????SHA?MD5?
web Support??Web??????Shiro????

5.Shiro??

??5.1 ?????

?????????

??

 

 

1.??????Web????
2.Shiro??????????Subject?????????????
3.SecurityManger ????????????????????
4.???????SecurityManger ???????????Subject?????????

5.2 ????

?????

??????jar?

??

????shiro.ini????
????shiro.ini??????????????
??1.shiro.ini????????????????ini
??2.shiro.ini??????classpath????

shiro.ini?????????

[main]   #????SecurityManager?????    ???=?????    ???.??[.??...] = ?    [users]   #?????????     ???= ??, ??1, ??2, …, ??N    [roles]   #????????     ???= ??1, ??2, …, ??N   #?????? * ????    [urls]    #??????????

?????????????:??:??

??shiro.ini???

##????   [users]   admin=123456,role_admin,role_user     ##????   [roles]   role_admin=*   role_user=modular:to_add,modular:add

?????

package com.gjs.shiro.test;    import org.apache.shiro.SecurityUtils;  import org.apache.shiro.authc.AuthenticationException;  import org.apache.shiro.authc.UsernamePasswordToken;  import org.apache.shiro.config.IniSecurityManagerFactory;  import org.apache.shiro.mgt.SecurityManager;  import org.apache.shiro.subject.Subject;    public class ShiroTest {      public static void main(String[] args) {          //?????????????????          IniSecurityManagerFactory factory =new IniSecurityManagerFactory("classpath:shiro.ini");          SecurityManager securityManager = factory.createInstance();          //??????SecurityUtils??????          SecurityUtils.setSecurityManager(securityManager);            //????????????????          Subject subject = SecurityUtils.getSubject();            //??????????token          UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");            //????????????????            try {              Subject resultSubject = securityManager.login(subject, token);                System.out.println("????");              System.out.println("????"+resultSubject.getPrincipal());              System.out.println("?????"+resultSubject.isPermitted("modular:add"));            } catch (AuthenticationException e) {              System.out.println("???????????????");              e.printStackTrace();          }        }  }

 

API???

IniSecurityManagerFactory?????ini??????SecurityManagerFactory??
SecurityManager??????????????Shiro???????????
SecurityUtils ?SecurityManager?????
Subject???????????????????
UsernamePasswordToken ????????????
IncorrectCredentialsException ???????
UnknownAccountException????????

6.Realm???

??????????????????ini????????????????????????????????????????????????????????
Shiro???Realm?????????????????????????????????

??6.1 ?????

??

????????????ini???????Realm?????Realm???????????

6.2 ???

?????

??????jar?

????????Realm

package com.gjs.shiro.realm;    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;    /**   * ?????Realm?????Realm AuthorizingRealm??????????   * @author gjs   *   */  public class MyRealm extends AuthorizingRealm{      /**       * ????? ????????subject?.??????????????????????????AuthenticationInfo??       */      @Override      protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {          System.out.println("????");          System.out.println("????" + token.getPrincipal());          if (token.getPrincipal().equals("admin")) {              //??1???????????????Subject??              //??2?????????Shiro????SimpleAuthenticationInfo??????              //??3:Realm???????Realm              return new SimpleAuthenticationInfo(token.getPrincipal(), "123456", this.getName());          }          return null;      }      /**       * ???????????????subject?????????????AuthorizationInfo????       */      @Override      protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {          SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();          info.addStringPermission("modular:add");//????          info.addRole("RoleAdmin");//????          return info;      }  }

????????shiro.ini????

[main]   ##??Realm??   myRealm=com.gjs.shiro.realm.MyRealm   ##??securityManager?realm???  ?????????????? $   securityManager.realms=$myRealm

???????????

package com.gjs.shiro.test;    import org.apache.shiro.SecurityUtils;  import org.apache.shiro.authc.AuthenticationException;  import org.apache.shiro.authc.UsernamePasswordToken;  import org.apache.shiro.config.IniSecurityManagerFactory;  import org.apache.shiro.mgt.SecurityManager;  import org.apache.shiro.subject.Subject;    public class ShiroTest {      public static void main(String[] args) {          //?????????????????          IniSecurityManagerFactory factory =new IniSecurityManagerFactory("classpath:shiro.ini");          SecurityManager securityManager = factory.createInstance();          //??????SecurityUtils??????          SecurityUtils.setSecurityManager(securityManager);            //????????????????          Subject subject = SecurityUtils.getSubject();            //??????????token          UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");            //????????????????            try {              Subject resultSubject = securityManager.login(subject, token);                System.out.println("????");              System.out.println("????"+resultSubject.getPrincipal());              System.out.println("?????"+resultSubject.isPermitted("modular:add"));              System.out.println("???RoleAdmin??:"+resultSubject.hasRole("RoleAdmin"));            } catch (AuthenticationException e) {              System.out.println("???????????????");              e.printStackTrace();          }        }  }

 

6.3 ??

????????????????????????????????????SimpleAuthenticationInfo????????????????shiro?????????????
??SimpleHash?????????Hash???
??HashedCredentialsMatcher?????Realm?????????Hash??
??ByteSource ???Hash??????

?????

????md5??

package com.gjs.shiro.test;    import org.apache.shiro.crypto.hash.Md5Hash;  import org.apache.shiro.util.ByteSource;    /**   * ????????????????????????   * @author gjs   *   */  public class Md5Util {      public static void main(String[] args) {          ByteSource salt = ByteSource.Util.bytes("gjs");          Md5Hash md5=new Md5Hash("123456", salt, 3);          String password = md5.toString();          System.out.println(password);      }  }

????ini????

[main]   ##??Realm??   myRealm=com.gjs.shiro.realm.MyRealm   #?????   credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher   ##??????. ??????set??   credentialsMatcher.hashAlgorithmName=md5   ##??????   credentialsMatcher.hashSalted=true   ##????   credentialsMatcher.hashIterations=3   ##?????????MyReam   myRealm.credentialsMatcher=$credentialsMatcher   ##??securityManager?realm???  ?????????????? $   securityManager.realms=$myRealm

????Realm??

package com.gjs.shiro.realm;    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;    /**   * ?????Realm?????Realm AuthorizingRealm??????????   * @author gjs   *   */  public class MyRealm extends AuthorizingRealm{      /**       * ????? ????????subject?.??????????????????????????AuthenticationInfo??       */      @Override      protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {          System.out.println("????");          System.out.println("????" + token.getPrincipal());          if (token.getPrincipal().equals("admin")) {              ByteSource salt = ByteSource.Util.bytes("gjs");              //??1???????????????Subject??              //??2?????????Shiro????SimpleAuthenticationInfo??????              //??3:Realm???????Realm              return new SimpleAuthenticationInfo(token.getPrincipal(), "a0af233bfd499995a8c1bacc4f61c489",salt, this.getName());          }          return null;      }      /**       * ???????????????subject?????????????AuthorizationInfo????       */      @Override      protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {          SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();          info.addStringPermission("modular:add");//????          info.addRole("RoleAdmin");//????          return info;      }  }?

??6.4 ?????????????JavaBean?Map?

?????????????????????????????????Shiro??????????????????????????????????????
???????????????????????JavaBean???Map
???????????????SimpleAuthenticationInfo??????????????????????????????????????????????????????

pojo???:

package com.gjs.shiro.pojo;    import java.util.Date;    public class User {      private int id;      private String name;      private String password;      private Date createDate;      private int status;      private Role role;        public Role getRole() {          return role;      }      public void setRole(Role role) {          this.role = role;      }      public int getId() {          return id;      }      public void setId(int id) {          this.id = id;      }      public String getName() {          return name;      }      public void setName(String name) {          this.name = name;      }      public String getPassword() {          return password;      }      public void setPassword(String password) {          this.password = password;      }      public Date getCreateDate() {          return createDate;      }      public void setCreateDate(Date createDate) {          this.createDate = createDate;      }      public int getStatus() {          return status;      }      public void setStatus(int status) {          this.status = status;      }      @Override      public String toString() {          return "User [id=" + id + ", name=" + name + ", password=" + password + ", createDate=" + createDate                  + ", status=" + status + ", role=" + role + "]";      }  }

package com.gjs.shiro.pojo;    import java.util.List;    public class Role {      private int roleId;      private String roleName;      private List<Perm> rolePerms;      public int getRoleId() {          return roleId;      }      public void setRoleId(int roleId) {          this.roleId = roleId;      }      public String getRoleName() {          return roleName;      }      public void setRoleName(String roleName) {          this.roleName = roleName;      }      public List<Perm> getRolePerms() {          return rolePerms;      }      public void setRolePerms(List<Perm> rolePerms) {          this.rolePerms = rolePerms;      }      @Override      public String toString() {          return "Role [roleId=" + roleId + ", roleName=" + roleName + ", rolePerms=" + rolePerms + "]";      }    }

package com.gjs.shiro.pojo;    public class Perm {      private int permId;      private String permName;      private String permAction;      private String permKey;      public int getPermId() {          return permId;      }      public void setPermId(int permId) {          this.permId = permId;      }      public String getPermName() {          return permName;      }      public void setPermName(String permName) {          this.permName = permName;      }      public String getPermAction() {          return permAction;      }      public void setPermAction(String permAction) {          this.permAction = permAction;      }      public String getPermKey() {          return permKey;      }      public void setPermKey(String permKey) {          this.permKey = permKey;      }      @Override      public String toString() {          return "Perm [permId=" + permId + ", permName=" + permName + ", permAction=" + permAction + ", permKey="                  + permKey + "]";      }    }

????Realm

package com.gjs.shiro.realm;    import java.util.ArrayList;  import java.util.Date;  import java.util.List;    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 com.gjs.shiro.pojo.Perm;  import com.gjs.shiro.pojo.Role;  import com.gjs.shiro.pojo.User;    /**   * ?????Realm?????Realm AuthorizingRealm??????????   * @author gjs   *   */  public class MyRealm extends AuthorizingRealm{      /**       * ????? ????????subject?.??????????????????????????AuthenticationInfo??       */      @Override      protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {          System.out.println("????");             User user=new User(); //?????????????          user.setId(1);          user.setName((String)token.getPrincipal());          user.setStatus(0);          user.setCreateDate(new Date());            if (token.getPrincipal().equals(user.getName())) {              ByteSource salt = ByteSource.Util.bytes("gjs");              //??1??????????????????              //??2?????????Shiro????SimpleAuthenticationInfo??????              //??3:????              //??4:Realm???????Realm              return new SimpleAuthenticationInfo(user, "a0af233bfd499995a8c1bacc4f61c489",salt, this.getName());          }          return null;      }      /**       * ???????????????subject?????????????AuthorizationInfo????       */      @Override      protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {          //??????          User user = (User) principals.getPrimaryPrincipal();          //?????????????????????          //??          Role role=new Role();          role.setRoleId(1);          role.setRoleName("RoleAdmin");          user.setRole(role);          //??          List<Perm> perms=new ArrayList<>();          Perm perm1=new Perm();          perm1.setPermId(1);          perm1.setPermName("????");          perm1.setPermAction("/user/toUserList");          perm1.setPermKey("user:to_edit");            perms.add(perm1);            role.setRolePerms(perms);            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();          info.addStringPermission(user.getRole().getRolePerms().get(0).getPermKey());//????          info.addRole(user.getRole().getName());//????          return info;      }  }

??????

package com.gjs.shiro.test;    import org.apache.shiro.SecurityUtils;  import org.apache.shiro.authc.AuthenticationException;  import org.apache.shiro.authc.UsernamePasswordToken;  import org.apache.shiro.config.IniSecurityManagerFactory;  import org.apache.shiro.mgt.SecurityManager;  import org.apache.shiro.subject.Subject;    import com.gjs.shiro.pojo.User;    public class ShiroTest {      public static void main(String[] args) {          //?????????????????          IniSecurityManagerFactory factory =new IniSecurityManagerFactory("classpath:shiro.ini");          SecurityManager securityManager = factory.createInstance();          //??????SecurityUtils??????          SecurityUtils.setSecurityManager(securityManager);            //????????????????          Subject subject = SecurityUtils.getSubject();            //??????????token          UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");            //????????????????            try {              Subject resultSubject = securityManager.login(subject, token);                System.out.println("????");              User user=(User) resultSubject.getPrincipal();//??????              System.out.println("????"+user.getName());              System.out.println("?????"+resultSubject.isPermitted("modular:add"));              System.out.println("???RoleAdmin??:"+resultSubject.hasRole("RoleAdmin"));                System.out.println("?????"+user.getRole());              System.out.println("????????"+user.getRole().getRolePerms().get(0));          } catch (AuthenticationException e) {              System.out.println("???????????????");              e.printStackTrace();          }        }  }

7.??API?

IniSecurityManagerFactory : ???????????SecurityManager??
SecurityManager ?????Shiro?????
SecurityUtils ?SecurityManager ????????Subject??
Subject ??????????????????????????
UsernamePasswordToken ??????? ?Token ??????????????
AuthorizingRealm ????????Realm
AuthenticationInfo ?????????????
SimpleAuthenticationInfo ?????????
Md5Hash Md5???
ByteSource ??????????????Md5???????
HashedCredentialsMatcher Md5??????????Md5??
AuthorizationInfo ??????????????
PrincipalCollection ???????????
SimpleAuthorizationInfo ??????????????