shiro初步 shiro认证

    xiaoxiao2025-12-16  11

    什么是shiro

    shiro是apache的一个开源框架,是一个权限管理的框架,实现 用户认证、用户授权。

    spring中有spring security (原名Acegi),是一个权限框架,它和spring依赖过于紧密,没有shiro使用简单。 shiro不依赖于spring,shiro不仅可以实现 web应用的权限管理,还可以实现c/s系统,分布式系统权限管理,shiro属于轻量框架,越来越多企业项目开始使用shiro。

    使用shiro实现系统 的权限管理,有效提高开发效率,从而降低开发成本。

    Jar包

    shrio基础jar包

    shiro架构

    subject:主体,可以是用户也可以是程序,主体要访问系统,系统需要对主体进行认证、授权。

    securityManager:安全管理器,主体进行认证和授权都 是通过securityManager进行。

    authenticator:认证器,主体进行认证最终通过authenticator进行的。

    authorizer:授权器,主体进行授权最终通过authorizer进行的。

    sessionManager:web应用中一般是用web容器对session进行管理,shiro也提供一套session管理的方式。 SessionDao: 通过SessionDao管理session数据,针对个性化的session数据存储需要使用sessionDao。

    cache Manager:缓存管理器,主要对session和授权数据进行缓存,比如将授权数据通过cacheManager进行缓存管理,和ehcache整合对缓存数据进行管理。

    realm:域,领域,相当于数据源,通过realm存取认证、授权相关数据。

    注意:在realm中存储授权和认证的逻辑。

    cryptography:密码管理,提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。 比如 md5散列算法。

    shiro认证流程

    shiro入门程序工程

    github下载shiro入门程序

    执行流程

    1、通过ini配置文件创建securityManager 2、调用subject.login方法主体提交认证,提交的token 3、securityManager进行认证,securityManager最终由ModularRealmAuthenticator进行认证。 4、ModularRealmAuthenticator调用IniRealm(给realm传入token) 去ini配置文件中查询用户信息 5、IniRealm根据输入的token(UsernamePasswordToken)从 shiro-first.ini查询用户信息,根据账号查询用户信息(账号和密码) 如果查询到用户信息,就给ModularRealmAuthenticator返回用户信息(账号和密码) 如果查询不到,就给ModularRealmAuthenticator返回null 6、ModularRealmAuthenticator接收IniRealm返回Authentication认证信息 如果返回的认证信息是null,ModularRealmAuthenticator抛出异常(org.apache.shiro.authc.UnknownAccountException) 如果返回的认证信息不是null(说明inirealm找到了用户),对IniRealm返回用户密码 (在ini文件中存在)和 token中的密码 进行对比,如果不一致抛出异常(org.apache.shiro.authc.IncorrectCredentialsException)

    小结 ModularRealmAuthenticator作用进行认证,需要调用realm查询用户信息(在数据库中存在用户信息) ModularRealmAuthenticator进行密码对比(认证过程)。

    realm:需要根据token中的身份信息去查询数据库(入门程序使用ini配置文件),如果查到用户返回认证信息,如果查询不到返回null。

    自定义realm

    realm接口

    需要在shiro-realm.ini配置realm注入到securityManager中

    [main] #自定义realm customRealm=com.hust.shiro.realm.CustomRealm #将realm设置到SecurityManager,相当于注入 securityManager.realm=$customRealm

    散列算法 加盐

    通常需要对密码 进行散列,常用的有md5、sha,

    对md5密码,如果知道散列后的值可以通过穷举算法,得到md5密码对应的明文。 建议对md5进行散列时加salt(盐),进行加密相当 于对原始密码+盐进行散列。 正常使用时散列方法: 在程序中对原始密码+盐进行散列,将散列值存储到数据库中,并且还要将盐也要存储在数据库中。

    如果进行密码对比时,使用相同 方法,将原始密码+盐进行散列,进行比对。

    在realm中配置凭证匹配器

    [main] #定义凭证匹配器 credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher #散列算法 credentialsMatcher.hashAlgorithmName=md5 #散列次数 credentialsMatcher.hashIterations=1 #自定义realm customRealm=com.hust.shiro.realm.CustomRealmMD5 customRealm.credentialsMatcher=$credentialsMatcher #将realm设置到SecurityManager,相当于注入 securityManager.realms=$customRealm 相关资源:shiro官方文档(中文)
    最新回复(0)