JAVA通过LDAP做用户登录认证,怎么做业务的异常处理?
高洛峰
高洛峰 2016-10-28 13:30:33
[Java讨论组]

通过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;    //否则登录失败
}


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(1)
三叔

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号