多个领域,用于处理Spring MVC和shiro中不同URL集的身份验证

时间:2014-07-03 06:27:42

标签: java spring-mvc authentication web.xml shiro

我正在努力为我的情况找到最佳实践解决方案。我的webapp中有两组不同的URL需要针对两组不同的用户群进行保护/身份验证。

例如,/ foo / * url只能由基于username / pwd标记的特定用户集访问。另一个set / bar / * url只能通过用户名/ pwd令牌机制访问一组用户(存储在第一组的不同数据库表中)。

我想了解如何在我的web.xml中构建shiro过滤器以及在applicationContext.xml中构造相应的shiro过滤器bean定义。我应该使用两个不同的shiro过滤器(每个url模式一个),映射到上下文文件中的两个不同的bean,其中每个bean都有自己的安全管理器,配置有自己的域(每个域负责对相应的身份验证)用户基表)。

我在这里关注这两个链接:

multi-tenancy-in-shiro

Multiple-security-managers...

但是我的应用程序出错了。在这里,我粘贴了一些示例代码。

的ApplicationContext-shiro.xml     

    <!-- 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="authenticator">
        <bean class="com.yatra.mp.security.MultiLoginAuthenticator"/>
    </property> -->

    <property name="cacheManager" ref="cacheManager" />
    <!-- Uncomment this next property if you want heterogenous session access 
        or clusterable/distributable sessions. The default value is 'http' which 
        uses the Servlet container's HttpSession as the underlying Session implementation. -->
</bean>`<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager" />
    <property name="unauthorizedUrl" value="/permissionDenied.do" />

    <!-- The 'filters' property is usually not necessary unless performing 
        an override, which we want to do here (make authc point to a PassthruAuthenticationFilter 
        instead of the default FormAuthenticationFilter: -->

    <property name="filters">
        <util:map>
            <entry key="adminAuthc" value-ref="adminAuthc" />
            <entry key="vendorAuthc" value-ref="vendorAuthc" />
            <entry key="adminUser" value-ref="adminUser" />
        </util:map>
    </property>
    <property name="filterChainDefinitions">
        <value>
            /admin/welcome.do = anon
            /vendor/welcome.do = anon
            /vendor/signup.do = anon
            /admin/signup.do = anon
            /assets/** = anon
            /admin/** = adminAuthc
            /vendor/** = vendorAuthc
        </value>
    </property>
</bean>
<bean id="adminAuthc"
    class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter">
    <property name="loginUrl" value="/admin/login.do" />
    <property name="successUrl" value="/admin/home.do" />
</bean>
<bean id="vendorAuthc"
    class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter">
    <property name="loginUrl" value="/vendor/login.do" />
    <property name="successUrl" value="/vendor/home.do" />
</bean>
<bean id="adminUser" class="org.apache.shiro.web.filter.authc.UserFilter">
    <property name="loginUrl" value="/admin/login.do" />
</bean>

<bean id="vendorUser" class="org.apache.shiro.web.filter.authc.UserFilter">
    <property name="loginUrl" value="/vendor/login.do" />
</bean>`

MultiLoginAuthenticator.java

public class MultiLoginAuthenticator extends ModularRealmAuthenticator {

@Override
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
    assertRealmsConfigured();   <------- Here I am getting null getRealms(). So I am getting exceptions
    MultiLoginAuthenticationToken mlat = null;
    Realm loginRealm = null;

    if (!(authenticationToken instanceof MultiLoginAuthenticationToken)) {
        throw new AuthenticationException("Unrecognized token , not a typeof MultiLoginAuthenticationToken ");
    } else {
        mlat = (MultiLoginAuthenticationToken) authenticationToken;
        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)) {
            return realm;
        }
    }
    throw new AuthenticationException("No realm configured for Client " + realmName);
}

}

当我配置MultiLoginAuthenticator时,我在getReamls()方法中得到null。所以它抛出了IllegalStateException。

如果我从applicationContext.xml文件中删除此Authenticator配置,则它能够正确登录,但它为“ doGetAuthorizationInfo ”方法调用不同的Realm。因此,它不会为当前主题分配任何角色和权限。

这是我的Realm文件(两个领域都是相同的。区别是调用不同的数据源。)

@Override
public boolean supports(AuthenticationToken token) {
    if (token instanceof MultiLoginAuthenticationToken) {
        return ((MultiLoginAuthenticationToken)token).getRealmName().equalsIgnoreCase("VendorAuthRealm");
    }
    return false;
}

@Override
protected AuthorizationInfo doGetAuthorizationInfo(
        PrincipalCollection principals) {
    logger.debug("authorization info.....");
    logger.debug("realm size is : {}", principals.fromRealm(getName()).size());
    logger.debug("realm name is : {}", principals.fromRealm(getName()));

    int userId = (Integer) principals.fromRealm(getName()).iterator().next();

    VendorUser vendorUser = vendorUserService.getVendorUser(userId);
    if(vendorUser != null) {
        logger.debug("vendor user first name is : {}", vendorUser.getFirstName());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(vendorUser.getVendorProducts() != null){
            logger.debug("vendor users products and rate types...");
            info.addRoles(VendorYatraUtil.getProductSet(vendorUser.getVendorProducts()));
            info.addStringPermissions(VendorYatraUtil.getCarRateTypeSet(vendorUser.getVendorCarRateTypes()));
        }
        return info;
    }
    return null;
}

@Override
protected AuthenticationInfo doGetAuthenticationInfo(
        AuthenticationToken authcToken) throws AuthenticationException {
    MultiLoginAuthenticationToken token = (MultiLoginAuthenticationToken) authcToken;
    logger.debug("username is : {}", token.getUsername());

    if(vendorUserService.findVendorUser(token.getUsername()) != null){
        VendorUser vendorUser = vendorUserService.findVendorUser(token.getUsername()); 
        if (vendorUser != null){
            return new SimpleAuthenticationInfo(vendorUser.getId(),
                    vendorUser.getPassword(), getName());
        }
    }

    return null;
}

谢谢, ANKIT

1 个答案:

答案 0 :(得分:1)

我现在已经解决了这个问题。

在applicationContext.xml文件中,Custom authenticator类的订单错放。我首先编写了authenticator属性,然后定义了Realms。

它正在成功验证...