shiro学习笔记

shiro架构

shiro学习笔记
SecurityManager:相当于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理。

Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了。

Authrizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能。

Subject:主体,可以看到主体可以是任何可以与应用交互的“用户”。

SessionManager:如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;这样的话,比如我们在Web环境用,刚开始是一台Web服务器;接着又上了台EJB服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器);

SessionDAO:DAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的SessionDAO,通过如JDBC写到数据库;比如想把Session放到Memcached中,可以实现自己的Memcached SessionDAO;另外SessionDAO中可以使用Cache进行缓存,以提高性能;

CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能

认证流程

创建SecurityManager → 主体认证 → SecurityManager认证 → Authenticator认证 → Realm验证

授权流程

创建SecurityManager → 主体授权 → SecurityManager授权 → Authorizer授权 → Realm获取角色权限数据

简单代码实现(模拟数据库)

pom依赖

        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>1.3.2</version>
        </dependency>

自定义Realm

public class ShanRealm extends AuthorizingRealm {
    String salt=getSalt();
    Map<String,String> usermap=new HashMap<>();
    {
        Md5Hash md5Hash=new Md5Hash("123456",salt);
        usermap.put("shan",md5Hash.toString());
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        AuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        String username=(String)principalCollection.getPrimaryPrincipal();
        Set<String> roles=getRolesByUserName(username);
        Set<String> permission=getPermissionByUserName(username);
        ((SimpleAuthorizationInfo) authorizationInfo).setRoles(roles);
        ((SimpleAuthorizationInfo) authorizationInfo).setStringPermissions(permission);
        return authorizationInfo;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username=(String)authenticationToken.getPrincipal();


        String password=getPassword(username);
        if(password==null){
            return null;
        }
        //加盐
        SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(username,password,"ShanRealm");
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(salt));
        return authenticationInfo;
    }
    private String getPassword(String username){
        return  usermap.get(username);
    }
    //获取角色
    private Set<String> getRolesByUserName(String userName){
        Set<String> sets=new HashSet<>();
        sets.add("admin");
        sets.add("user");
        return sets;
    }
    //获取权限
    private Set<String> getPermissionByUserName(String userName){
        Set<String> sets=new HashSet<>();
        sets.add("user:delete");
        sets.add("user:add");
        return sets;
    }

 //生成盐
 private static String getSalt(){
     SecureRandom random = new SecureRandom();
     byte bytes[] = new byte[15];
     random.nextBytes(bytes);
     String salt =encodeBase64String(bytes);
     return salt;
 }
}

主体登录

   //1.创建SecurityManager及自定义Realm
        ShanRealm shanRealm=new ShanRealm();
        DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
        defaultSecurityManager.setRealm(shanRealm);
        //2.md5加密
        HashedCredentialsMatcher hashedCredentialsMatcher=new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(1);
        shanRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        //3.创建主体subject,主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject =SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("shan","123456");
        subject.login(usernamePasswordToken);
        System.out.println(subject.isAuthenticated());
        //4.检验角色及权限
        subject.checkRoles("admin","user");
        subject.checkPermissions("user:delete","user:add");
       ```