多个java servlet身份验证方法

时间:2010-06-18 02:39:53

标签: java

是否可以为java servlet提供多种身份验证方法?例如,除了基于open id的身份验证之外,还具有基于表单的身份验证,以便用户可以选择他们的登录方式。

3 个答案:

答案 0 :(得分:7)

但是,我建议使用servlet过滤器而不是servlet本身。

http://brendangraetz.wordpress.com/2010/06/17/use-servlet-filters-for-user-authentication/

按照该帖子中的步骤操作,并覆盖isAuth()方法,以便在您希望的多种模式下执行身份验证。在(非常粗略,未经测试)代码中:

@Override protected boolean isAuth()
{
    String authMode = (String)(getSession(true).getAttribute("authMode"));
    if (authMode == null) { return false; }
    if (authMode.equals("open id") {
        //do open id authentication steps here
        //return true if authentication passes
    }
    else if (authMode.equals("some other authentication") {
        //do some other authentication steps here
        //return true if authentication passes
    }
    ...
    return false;    
}

我当然假设您已经知道如何在每种模式下单独实施身份验证步骤。

“技巧”是在HTTP会话中,在用户执行身份验证登录后立即在HTTP会话中存储值。基于此值,过滤器将在加载servlet之前知道应该检查或查询您指定的内容。

答案 1 :(得分:1)

执行多重身份验证的另一种方法是使用JAAS,即Java身份验证和授权服务。使用JAAS,您可以将各种身份验证模块堆叠在一起,并且可以配置要运行哪个身份验证模块以及不运行哪个身份验证模块。这称为PAM(可插拔认证模块)。在Google上搜索“J2SE JAAS”或查看http://server.pramati.com/docstore/1270002/index.htm。如果你决定走这条路,这些应该可以帮助你开始。

答案 2 :(得分:0)

是的,这是可能的,但实施起来往往有点棘手。

例如,开箱即用的SpringSecurity支持本地身份验证,OpenId,X509和其他方案,但是将它们组合起来以便用户有其他登录方式需要自定义类和自定义连接。