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

标签 java spring-mvc authentication web.xml shiro

我正在尝试寻找适合我的情况的最佳实践解决方案。我的 web 应用程序中有两组不同的 url,需要针对两组不同的用户群进行安全保护/身份验证。

例如,/foo/* url 只能由基于用户名/密码 token 的特定用户组访问。另一组/bar/* url 只能通过用户名/密码 token 机制由一组用户访问(存储在与第一组不同的数据库表中)。

我想了解如何在 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 文件中删除此身份 validator 配置,那么它可以正确登录,但它会为“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;
}

谢谢, 安基特

最佳答案

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

在 applicationContext.xml 文件中,自定义 validator 类的顺序错误。我先编写了authenticator属性,然后定义了Realms。

认证成功...

关于java - Spring MVC 和 shiro 中的多个领域用于处理不同 url 集的身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24546396/

相关文章:

java - 返回按钮编辑操作

Java线程同步块(synchronized block)行为-synchronized与synchronized()?

spring - 使用 Spring MVC 时无法让 Tomcat 提供一些静态文件

session - 具有多个域的 ColdFusion session 管理/用户身份验证

ruby-on-rails - rails ,设计 : how to replace previous login via token authentication

java - 如何从 git 克隆存储库并在 java 中自动运行 maven build

java - okHTTP POST 请求正文有很多子项

java - 与四郎一起度过 Spring

java - 无法启动 Spring Boot 应用程序

c# - ASP.NET Web Api 身份验证方法