springboot shiro 多realm配置认证、受权

shiro进行登陆认证和权限管理的实现。其中需求涉及使用两个角色分别是:门店,公司。如今要二者实现分开登陆。即须要两个Realm——MyShiroRealmSHOP和MyShiroRealmCOMPANY,分别处理门店,公司的验证功能。java

可是正常状况下,当定义了多个Realm,不管是门店登陆仍是公司登陆,都会由这两个Realm共同处理。这是由于,当配置了多个Realm时,咱们一般使用的认证器是shiro自带的org.apache.shiro.authc.pam.ModularRealmAuthenticator,其中决定使用的Realm的是doAuthenticate()方法,源代码以下:redis

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);
        }
    }

  

上述代码的意思就是若是有多个Realm就会使用全部配置的Realm。 只有一个的时候,就直接使用当前的Realm。spring

为了实现需求,我会建立一个org.apache.shiro.authc.pam.ModularRealmAuthenticator的子类,并重写doAuthenticate()方法,让特定的Realm完成特定的功能。如何区分呢?我会同时建立一个org.apache.shiro.authc.UsernamePasswordToken的子类,在其中添加一个字段VirtualType,用来标识登陆的类型,便是门店登陆仍是公司登陆。具体步骤以下:apache

public enum VirtualType {
    COMPANY,        // 公司
    SHOP            // 门店
}

  接下来新建org.apache.shiro.authc.UsernamePasswordToken的子类UserToken缓存

import org.apache.shiro.authc.UsernamePasswordToken;

public class UserToken extends UsernamePasswordToken {
    private VirtualType virtualType;

    public UserToken(final String username, final String password, VirtualType virtualType) {
        super(username, password);
        this.virtualType = virtualType;
    }

    public VirtualType getVirtualType() {
        return virtualType;
    }

    public void setVirtualType(VirtualType virtualType) {
        this.virtualType = virtualType;
    }
}

  新建org.apache.shiro.authc.pam.ModularRealmAuthenticator的子类UserModularRealmAuthenticator:ide

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

public class UserModularRealmAuthenticator extends ModularRealmAuthenticator {

    private static final Logger logger = LoggerFactory.getLogger(UserModularRealmAuthenticator.class);

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        logger.info("UserModularRealmAuthenticator:method doAuthenticate() execute ");
        // 判断getRealms()是否返回为空
        assertRealmsConfigured();
        // 强制转换回自定义的CustomizedToken
        UserToken userToken = (UserToken) authenticationToken;
        // 登陆类型
        VirtualType virtualType = userToken.getVirtualType();
        // 全部Realm
        Collection<Realm> realms = getRealms();
        // 登陆类型对应的全部Realm
        Collection<Realm> typeRealms = new ArrayList<>();
        for (Realm realm : realms) {
            if (realm.getName().contains(virtualType.toString()))  // 注:这里使用类名包含枚举,区分realm
                typeRealms.add(realm);
        }
        // 判断是单Realm仍是多Realm
        if (typeRealms.size() == 1) {
            logger.info("doSingleRealmAuthentication() execute ");
            return doSingleRealmAuthentication(typeRealms.iterator().next(), userToken);
        } else {
            logger.info("doMultiRealmAuthentication() execute ");
            return doMultiRealmAuthentication(typeRealms, userToken);
        }
    }
}

  建立分别处理门店登陆仍是公司登陆的Realm: ui

import org.apache.shiro.authc.*;
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.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**公司登录realm
 */
public class MyShiroRealmCOMPANY extends AuthorizingRealm {

    @Autowired
    IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal(); // 必定是String类型,在SimpleAuthenticationInfo
        SystemUser systemUser = userService.getUserByName(username, VirtualType.COMPANY);
        if (systemUser == null) {
            throw new RuntimeException("system concurrent exception: COMPANY user not found:username=" + username);
        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        Set<String> stringPermissions = new HashSet<>(256);
     // 字符串资源 authorizationInfo.addStringPermissions(stringPermissions); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { // UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; UserToken token = (UserToken)authenticationToken;
// 逻辑登录 return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName()); } }

  

import org.apache.shiro.authc.*;
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.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**门店登录realm
 */
public class MyShiroRealmSHOP extends AuthorizingRealm {

    @Autowired
    IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal(); // 必定是String类型,在SimpleAuthenticationInfo
        SystemUser systemUser = userService.getUserByName(username, VirtualType.SHOP);
        if (systemUser == null) {
            throw new RuntimeException("system concurrent exception: SHOP user not found:username=" + username);
        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        Set<String> stringPermissions = new HashSet<>(256);
     // 字符串资源
        authorizationInfo.addStringPermissions(stringPermissions);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserToken token = (UserToken)authenticationToken;
        // 逻辑登录
        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
    }
}

  ShiroConfig配置this

@Bean("securityManager")
    public SecurityManager securityManager(RedisTemplate redisTemplate) {          // redisTemplate配置的redis缓存,可忽略
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        List<Realm> realms = new ArrayList<>();
        //添加多个Realm
        realms.add(myShiroRealmSHOP(redisTemplate));
        realms.add(myShiroRealmCOMPANY(redisTemplate));
        securityManager.setAuthenticator(modularRealmAuthenticator());          // 须要再realm定义以前
        securityManager.setRealms(realms);
        securityManager.setSessionManager(myShiroSession(redisTemplate));
        return securityManager;
    }

    /**
     * 系统自带的Realm管理,主要针对多realm 认证
     */
    @Bean
    public ModularRealmAuthenticator modularRealmAuthenticator() {
        //本身重写的ModularRealmAuthenticator
        UserModularRealmAuthenticator modularRealmAuthenticator = new UserModularRealmAuthenticator();
        modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        return modularRealmAuthenticator;
    }

    @Bean("myShiroRealmSHOP")
    public MyShiroRealmSHOP myShiroRealmSHOP(RedisTemplate redisTemplate) {
        return new MyShiroRealmSHOP();
    }

    @Bean("myShiroRealmCOMPANY")
    public MyShiroRealmCOMPANY myShiroRealmCOMPANY(RedisTemplate redisTemplate) {
        return new MyShiroRealmCOMPANY();
    }

  登录便可:.net

subject.login(new UserToken(username, password, virtualType))  

 

这里须要注意的是,上述配置的Authenticator主要针对登录认证,对于受权时没有控制的,使用资源注入时会发现,使用的是myShiroRealmSHOP的doGetAuthorizationInfo方法(上面SHOP的定义在前),没有走对应的realm的受权,产生问题错乱;code

新建org.apache.shiro.authz.ModularRealmAuthorizer子类:

import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserModularRealmAuthorizer extends ModularRealmAuthorizer { @Override public boolean isPermitted(PrincipalCollection principals, String permission) { assertRealmsConfigured(); for (Realm realm : getRealms()) { if (!(realm instanceof Authorizer)){ continue;} // todo 受权配置 if (realm.getName().contains(VirtualType.COMPANY.toString())) {    // 判断realm if (permission.contains("company")) {    // 判断是否改realm的资源 return ((MyShiroRealmCOMPANY) realm).isPermitted(principals, permission); // 使用改realm的受权方法 } } if (realm.getName().contains(VirtualType.SHOP.toString())) { if (permission.contains("shop")) { return ((MyShiroRealmSHOP) realm).isPermitted(principals, permission); } } } return false; } }

  而后在ShiroConfig更改:

@Bean("securityManager")
    public SecurityManager securityManager(RedisTemplate redisTemplate) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 使用注解,@RequiresPermissions,读取缓存权限信息保存key对象为:{@link org.apache.shiro.subject.SimplePrincipalCollection},因此redis缓存配置的String不能转换
//        securityManager.setCacheManager(redisCacheManager(redisTemplate));
        List<Realm> realms = new ArrayList<>();
        //添加多个Realm
        realms.add(myShiroRealmSHOP(redisTemplate));
        realms.add(myShiroRealmCOMPANY(redisTemplate));
        securityManager.setAuthenticator(modularRealmAuthenticator());
        securityManager.setAuthorizer(modularRealmAuthorizer());    // 这里
        securityManager.setRealms(realms);
        securityManager.setSessionManager(myShiroSession(redisTemplate));
        return securityManager;
    }

    /**
     * 系统自带的Realm管理,主要针对多realm 认证
     */
    @Bean
    public ModularRealmAuthenticator modularRealmAuthenticator() {
        //本身重写的ModularRealmAuthenticator
        UserModularRealmAuthenticator modularRealmAuthenticator = new UserModularRealmAuthenticator();
        modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        return modularRealmAuthenticator;
    }

    /**
     * 系统自带的Realm管理,主要针对多realm 受权
     */
    @Bean
    public ModularRealmAuthorizer modularRealmAuthorizer() {
        //本身重写的ModularRealmAuthorizer
        UserModularRealmAuthorizer modularRealmAuthorizer = new UserModularRealmAuthorizer();
        return modularRealmAuthorizer;
    }

    @Bean("myShiroRealmSHOP")
    public MyShiroRealmSHOP myShiroRealmSHOP(RedisTemplate redisTemplate) {
        return new MyShiroRealmSHOP();
    }

    @Bean("myShiroRealmCOMPANY")
    public MyShiroRealmCOMPANY myShiroRealmCOMPANY(RedisTemplate redisTemplate) {
        return new MyShiroRealmCOMPANY();
    }

  

参考:https://blog.csdn.net/cckevincyh/article/details/79629022 

相关文章
相关标签/搜索