java ldap 认证,使用用户名的Java LDAP身份验证

Ok, this is driving me crazy. I'm trying to create an LDAP authentication with Java and everything is fine if I use my First name and Last name in the SECURITY_PRINCIPAL. This is my code:

try {

Hashtable ldapEnv = new Hashtable();

ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

ldapEnv.put(Context.PROVIDER_URL, "LDAP://myldap.mydomain.com:389");

ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");

ldapEnv.put(Context.SECURITY_PRINCIPAL, "CN=FirstName LastName" + ",ou=Users");

ldapEnv.put(Context.SECURITY_CREDENTIALS, "password");

DirContext ldapContext = new InitialLdapContext(ldapEnv, null);

}

catch (Exception e) {

System.out.println(" bind error: " + e);

e.printStackTrace();

}

The problem is that it does not work with my username. If I try:

ldapEnv.put(Context.SECURITY_PRINCIPAL, "CN=myusername" + ",ou=Users");

Or

ldapEnv.put(Context.SECURITY_PRINCIPAL, "uid=myusername" + ",ou=Users");

I always get [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1]

This only seems to work with my First name and Last name for some reason. I checked the AD and my sAMAccountName is my correct username. Not sure why this is happening. Anyone else had such issues? Can I pass something else to Context.SECURITY_PRINCIPAL? I tried ldapEnv.put(Context.SECURITY_PRINCIPAL, "sAMAccountName=myusername" + ",ou=Users"); but it also fails... Can anyone please help?

解决方案

EJP, thanks for your input. You are indeed correct but I was looking for something simple - just pass a username and password to the AD and see if it authenticates or not .I should have been more specific in my first post. Your suggestion will work but I think this is much simpler:

Hashtable props = new Hashtable();

String principalName = "username@mydomain.com";

props.put(Context.SECURITY_PRINCIPAL, principalName);

props.put(Context.SECURITY_CREDENTIALS, "mypassword");

DirContext context;

//try to authenticate

try {

context = com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance("LDAP://myldap.mydomain.com:389" + '/', props);

context.close();

}

This way I don't care about the DN. Just passing the username@domain and voila - works like a charm :) Thanks again!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值