多个java servlet身份验证方法

knp*_*wrs 5 java

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

bgu*_*uiz 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;    
}
Run Code Online (Sandbox Code Playgroud)

我当然假设你已经知道如何分别在每种模式下实现身份验证步骤.

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