我是 Spring 和 Shiro 平台的新手。
我有两个网址集 /admin/--
和 /vendor/--
。两个客户端集都使用特定领域进行身份验证。我扩展了 ModularRealmAuthenticator
类来选择正确的领域进行身份验证。
ModularRealmAuthenticator.java
@Override
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
assertRealmsConfigured();
MultiLoginAuthenticationToken mlat = null;
Realm loginRealm = null;
if (!(authenticationToken instanceof MultiLoginAuthenticationToken)) {
throw new AuthenticationException("Unrecognized token , not a typeof MultiLoginAuthenticationToken ");
} else {
mlat = (MultiLoginAuthenticationToken) authenticationToken;
logger.debug("realm name is : {}", mlat.getRealmName());
loginRealm = lookupRealm(mlat.getRealmName());
}
return doSingleRealmAuthentication(loginRealm, mlat);
}
protected Realm lookupRealm(String realmName) throws AuthenticationException {
Collection<Realm> realms = getRealms();
for (Realm realm : realms) {
if (realm.getName().equalsIgnoreCase(realmName)) {
logger.debug("look up realm name is : {}", realm.getName());
return realm;
}
}
throw new AuthenticationException("No realm configured for Client " + realmName);
}
但是,当我将来自不同数据源集的角色和权限分配给两个客户端(管理员和供应商)时。它按照我在 applicationContext.xml 文件中定义的顺序迭代领域。
我的ApplicationContext.xml
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="authenticator">
<bean class="com.yatra.mp.security.MultiLoginAuthenticator"/>
</property>
<!-- Single realm app (realm configured next, below). If you have multiple
realms, use the 'realms' property instead. -->
<property name="realms">
<util:list>
<ref bean="adminAuthRealm" />
<ref bean="vendorAuthRealm" />
</util:list>
</property>
<property name="cacheManager" ref="cacheManager" />
</bean>
这两个领域都扩展了 AuthorizingRealm 类,并且都有 doGetAuthorizationInfo 和 doGetAuthenticationInfo 方法。我在其中定义了我的自定义实现。
是否有必要扩展ModularRealmAuthorizer类?如果是,您能告诉我我覆盖了哪个方法吗?
最佳答案
您可以做的是将域信息添加到您可以包装在 AuthenticationInfo 中的PrincipalCollection。它是主体集合中添加的 token ,会在后续的 shiro 调用中继承。如果它与您的领域不匹配,您可以在身份验证中使用该信息来跳过。这实际上是我们在自定义领域中所做的事情:
public class OurRealmImpl extends AuthorizingRealm
...
@Override
public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
... //check if user exists and read passwordhash
Login ourLoginToken = ...
SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(ourLoginToken, realmName);
return new SimpleAuthenticationInfo(principalCollection, passwordHash);
}
@Override
public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Collection collection = principals.fromRealm(realmName);
if (collection.isEmpty()) {
return null;
}
Login login = (Login) collection.iterator().next();
... get the rights and return authorization
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermissions(permissionStrings);
return info;
}
关于java - Shiro中如何从多个领域中获取特定领域进行授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24576987/