shiro架构图及执行流程详解

1、shiro架构图

shiro基本架构图:

在这里插入图片描述

Subject: 主体,可以是任何可以与应用交互的“用户”;
SecurityManager: 相当于SpringMVC中的DispatcherServlet,是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理。
Authenticator: 认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;
Authrizer: 授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;
Realm: 可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提供;注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm;
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: 缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能
Cryptography: 密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的。

以上部分参考https://www.cnblogs.com/flyuphigh/p/8058454.html

2、shiro基本流程

一个简单的Shiro应用:
在这里插入图片描述

1、应用代码通过Subject来进行认证和授权,而Subject又委托给SecurityManager;
2、我们需要给Shiro的SecurityManager注入Realm,从而让SecurityManager能得到合法的用户及其权限进行判断。
Shiro不提供维护用户/权限,而是通过Realm让开发人员自己注入

实际开发中,使用shiro来控制权限,一般有三个基本对象:
1、 权限对象Persimmsion

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Permission{
    private String id;
    private String name;
    private String url;
}

2、 角色对象Role

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Role{
    private String id;
    private String name;
    //权限集合
    private List<Permission> permissions;
}

3、 用户对象User

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User{
    private String id;
    private String username;
    private String password;
    //定义角色
    List<Role> roleList;
}

用户拥有哪些角色,角色中包含哪些权限操作,从而来管理用户是否有权限来执行一些操作。

接下来便是配置shiro:
1、自定义Realm

public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("调用授权验证:"+primaryPrincipal);
        User user = userService.findRolesByUserName(primaryPrincipal);
        if (!CollectionUtils.isEmpty(user.getRoleList())) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            for (Role role : user.getRoleList()) {
                simpleAuthorizationInfo.addRole(role.getName());

                //权限信息
                List<Permission> permissions = userService.findPermissionsByRoleId(role.getId());
                if(!CollectionUtils.isEmpty(permissions)){
                    for (Permission p : permissions) {
                        simpleAuthorizationInfo.addStringPermission(p.getName());
                    }
                }
            }
            return simpleAuthorizationInfo;
        }

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        User user = userService.findByUserName(principal);

        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(),
                    user.getPassword(),
                    new MyByteSource(user.getSalt()),
                    //ByteSource.Util.bytes(user.getSalt().getBytes()),
                    this.getName());
        }

        return null;
    }
}

本文所附代码不细看具体细节,这里只总结大致流程,自定义CustomerRealm 继承抽象类 AuthorizingRealm,并实现其两个抽象方法doGetAuthorizationInfo与doGetAuthenticationInfo,两者分别获取数据库中当前Subject(即用户User)的权限信息和认证信息(即密码验证),一般数据库表中权限和角色关系都是多对多,我们可以联表查询到当前用户所有角色中所有权限值。总的来看,自定义CustomerRealm会分别把权限信息与认证密码信息分别封装,以便调用这两个方法时返回数据库中数据。

2、定义配置类shiroConfig

@Configuration
public class ShiroConfig {

    //1.创建shiroFilter  //负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //配置系统受限资源  公共资源
        Map<String, String> stringStringMap = new HashMap<String, String>();
        stringStringMap.put("/index.jsp","authc"); //请求该页面需要认证和授权

       //默认认证界面路径
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(stringStringMap);
        return shiroFilterFactoryBean;
    }

    //2.创建SecurityManager
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //给安全管理器设置realm
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    //3.创建自定义Realm
    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        hashedCredentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        //开启缓存管理
        customerRealm.setCacheManager(new RedisCacheManager());
        //开启全局缓存
        customerRealm.setCachingEnabled(true);
        //开启认证缓存
        customerRealm.setAuthenticationCachingEnabled(true);
        customerRealm.setAuthenticationCacheName("AuthenticationCache");
        //开启授权缓存
        customerRealm.setAuthorizationCachingEnabled(true);
        customerRealm.setAuthorizationCacheName("AuthorizationCache");

        return customerRealm;
    }
}

这里配置了三个Bean,顺序是

  1. 获取ShiroFilterFactoryBean,作用是类似于AOP,执行相关操作前,先进行功能过滤,拦截所有请求,进入到shiro中进行认证与授权
  2. 创建SecurityManager,它是shiro的心脏,来管理shiro
  3. 对自定义的CustomerRealm进行一些配置,比如配置凭证校验匹配器了、设置reids缓存了

从三个方法传入参数来看,是呈链式调用的,getShiroFilterFactoryBean()方法需要传入DefaultWebSecurityManager对象,getDefaultWebSecurityManager()方法需要传入Realm(Realm是个接口)实际传入的是getRealm()方法返回的CustomerRealm对象。
这些靠spring来自动注入(@Bean作用的方法,spring会为其自动注入所需入参对象,spring自动匹配所需入参类型来注入,如果有多个匹配,我们需要为bean起名字,通过来指定要传入的对象,比如为Realm起名字@Bean(value = “myRealm”),如getDefaultWebSecurityManager(@Qualifier(value = “myRealm”) Realm realm))

事实上,每个Bean对应的方法名可以改变,比如getRealm()可以改为getMyRealm(),然后对应的defaultWebSecurityManager.setRealm(realm);改为defaultWebSecurityManager.setRealm(getMyRealm());即可

配置完后,看实际执行流程(以认证为例):
1、切入点在subject.login()

@PostMapping("/login/{username}/{password}")
public String login(@PathVariable("username") String username,
                    @PathVariable("password") String password){
    Subject subject = SecurityUtils.getSubject();
    try{
        subject.login(new UsernamePasswordToken(username,password));
        return "success!!!";
    }catch (UnknownAccountException e){
        e.printStackTrace();
        return "用户名错误!!!";
    }catch (IncorrectCredentialsException e){
        e.printStackTrace();
        return "密码错误!!!";
    }
}

2、Subject是个接口,这里的login方法由DelegatingSubject实现

public class DelegatingSubject implements Subject {

可以看到,DelegatingSubject中的login()方法又调用了SecurityManager的login()方法
注意调试的时候,要下载shiro框架的源码来查看对应的java文件,不要去看class文件里的东西,java文件里更清晰

public void login(AuthenticationToken token) throws AuthenticationException {
    clearRunAsIdentitiesInternal();
    Subject subject = securityManager.login(this, token);

3、进入securityManager.login()方法,发现执行的是DefaultSecurityManager的login()方法,并调用了authenticate()方法,其中DefaultSecurityManager继承的父类实现了SecurityManager接口

public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
    AuthenticationInfo info;
    try {
        info = authenticate(token);

4、这个authenticate()方法属于抽象类AuthenticatingSecurityManager,转而调用了this.authenticator的authenticate()方法,

public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
    return this.authenticator.authenticate(token);
}

5、这个this.authenticator是该抽象类中定义的private Authenticator authenticator; Authenticator 是个接口,实际执行的是其实现类AbstractAuthenticator的authenticate()方法

public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
    if (token == null) {
        throw new IllegalArgumentException("Method argument (authentication token) cannot be null.");
    }
    log.trace("Authentication attempt received for token [{}]", token);

    AuthenticationInfo info;
    try {
        info = doAuthenticate(token);

6、AbstractAuthenticator是个抽象类,并执行了其doAuthenticate()方法,该方法是个抽象方法,实际执行的是其实现类ModularRealmAuthenticator中的方法

protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
    assertRealmsConfigured();
    Collection<Realm> realms = getRealms();
    if (realms.size() == 1) {
        return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
    } else {
        return doMultiRealmAuthentication(realms, authenticationToken);
    }
}

这里有个疑问:getRealms()如何获取到realm的,查看了对应方法,只看见传参,没看见从哪来的…不过最开始的确配置了defaultWebSecurityManager.setRealm(realm);不然这里会报错

回去补习了一下@Bean作用,,,猜测这个realm是直接从Spring容器中得到的,这是我们前边@Bean配置的getRealm()返回的自定义CustomerRealm对象

7、进入当前类下的doSingleRealmAuthentication()方法,然后去执行realm.getAuthenticationInfo()方法。

protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
    if (!realm.supports(token)) {
        String msg = "Realm [" + realm + "] does not support authentication token [" +
                token + "].  Please ensure that the appropriate Realm implementation is " +
                "configured correctly or that the realm accepts AuthenticationTokens of this type.";
        throw new UnsupportedTokenException(msg);
    }
    AuthenticationInfo info = realm.getAuthenticationInfo(token);

8、Realm是个接口,实际调用的是抽象类AuthenticatingRealm的方法

public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    AuthenticationInfo info = getCachedAuthenticationInfo(token);
    if (info == null) {
        //otherwise not cached, perform the lookup:
        info = doGetAuthenticationInfo(token);
    ......//省略一部分
    if (info != null) {
            assertCredentialsMatch(token, info);
        }

9、先从缓存中取,若取不到,则执行doGetAuthenticationInfo()方法,绕了这么久终于来了!!!还记得自定义的CustomerRealm 继承 抽象类AuthorizingRealm,并实现了其两个抽象方法,其中一个就是认证的doGetAuthenticationInfo(),这里从数据库读取用户名密码。

10、然后进入assertCredentialsMatch方法中进行密码校验,token中是new UsernamePasswordToken(username,password)前端传进来的用户名密码,info中是数据库查到的用户名密码及随机盐。

protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
        CredentialsMatcher cm = getCredentialsMatcher();
        if (cm != null) {
            if (!cm.doCredentialsMatch(token, info)) {
                //not successful - throw an exception to indicate this:
                String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
                throw new IncorrectCredentialsException(msg);
            }

11、cm.doCredentialsMatch(token, info)方法是由我们realm中指定的密码校验器HashedCredentialsMatcher实现的,在这里完成校验。到这里就不继续看了。。。

public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        Object tokenHashedCredentials = hashProvidedCredentials(token, info);
        Object accountCredentials = getCredentials(info);
        return equals(tokenHashedCredentials, accountCredentials);
    }

授权的话现在使用一般都是在controller里的每个请求方法前加注解如:

@RequiresPermissions("/user/login")@RequiresRoles("admin")

在config配置类中加入以下配置,使注解生效

	//配置使@RequiresPermissions起作用
	@Bean 
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor
            = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

对应数据库中权限值或角色值,来进行权限控制。

另外shiro认证成功后,会把Subject(当前用户)信息保存到session(使用SecurityUtils.getSubject().getSession().setAttribute()可以自己往session中添加信息),服务器为每个用户生成session及cookie并将各自唯一的sessionId放到cookie中返回给浏览器,当访问其他需要认证或授权接口时,通过sessionId判断是否已认证,若session已过期,则校验不通过,需要重新登录。
而权限信息不会保存,每次访问需要鉴权接口需要重新执行doGetAuthorizationInfo()方法,可以打断点测试。所以可以配置对应的CacheManager比如使用redis做缓存提升效率,同时可以实现分布式session管理,相关用法教程比较多就不说明了~

  • 20
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值