Home  >  Q&A  >  body text

JAVA通过LDAP做用户登录认证,怎么做业务的异常处理?

通过java.namming包实现LDAP用户登录认证,怎么区分账号被冻结、停用、不存在等异常的业务情况呢?

参考的是:网上普遍流传的LDAP连接的代码

public boolean auth(String username, String password) {
    //设置相关常量
    String initialContextFactory ="com.sun.jndi.ldap.LdapCtxFactory";
    String ad4ProviderURL ="ldap://ip:port";
    String securityAuthentication ="simple";
    String domain ="ad4";

    if (!username.startsWith(domain)) {
        username = domain+"\"+ username;
    }

    /*
     * 组织参数集合
     */
    Hashtable<String,String> env = new Hashtable<String,String>();
    //set the initializing information of the context
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    //set the URL of ldap server
    env.put(javax.naming.Context.PROVIDER_URL, ad4ProviderURL);
    //set the authentication mode
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, securityAuthentication);
    //set user of AD
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, username);
    //set password of user
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, password);

    /*
     * 进行LDAP连接
     */
    javax.naming.ldap.LdapContext ctx = null;
    //initialize the ldap context
    try {
        ctx = new javax.naming.ldap.InitialLdapContext(env, null);
    } catch (javax.naming.NamingException ex) {
        System.out.println("Authentication error, username is:"+ username);
        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (javax.naming.NamingException ex) {
                System.out.println("Close Authentication context error");
                ex.printStackTrace();
            }
            return true;    //获取的LdapContext对象不为空,则为登录成功
        }
    }
    return false;    //否则登录失败
}


高洛峰高洛峰2818 days ago731

reply all(1)I'll reply

  • 三叔

    三叔2016-10-28 13:31:01

    user表中存储着user_status,定义用户的状态。

    reply
    0
  • Cancelreply