这就是第三方验证。一般有AD域,Ldap,Radius,邮件服务器等。最常用的要数AD域了。因为window系统在国内占据了大量的江山。做起来也很方便。
我这篇文章就是写,如何用java去实现AD域的身份验证。好了,直接看代码吧:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
package
com.test;
import
java.util.Hashtable;
import
javax.naming.AuthenticationException;
import
javax.naming.Context;
import
javax.naming.directory.DirContext;
import
javax.naming.directory.InitialDirContext;
/**
* 使用java连接AD域,验证账号密码是否正确
* @author Herman.Xiong
* @date 2014-12-23 下午02:07:26
* @version V3.0
* @since jdk 1.6,tomcat 6.0
*/
public
class
AdTest {
/**
* 使用java连接AD域
* @author Herman.Xiong
* @date 2014-12-23 下午02:24:04
* @return void
* @throws 异常说明
* @param host 连接AD域服务器的ip
* @param post AD域服务器的端口
* @param username 用户名
* @param password 密码
*/
public
static
void
connect(String host,String post,String username,String password) {
DirContext ctx=
null
;
Hashtable<string,string> HashEnv =
new
Hashtable<string,string>();
HashEnv.put(Context.SECURITY_AUTHENTICATION, simple);
// LDAP访问安全级别(none,simple,strong)
HashEnv.put(Context.SECURITY_PRINCIPAL, username);
//AD的用户名
HashEnv.put(Context.SECURITY_CREDENTIALS, password);
//AD的密码
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,com.sun.jndi.ldap.LdapCtxFactory);
// LDAP工厂类
HashEnv.put(com.sun.jndi.ldap.connect.timeout,
3000
);
//连接超时设置为3秒
HashEnv.put(Context.PROVIDER_URL, ldap:
// + host + : + post);// 默认端口389
try
{
ctx =
new
InitialDirContext(HashEnv);
// 初始化上下文
System.out.println(身份验证成功!);
}
catch
(AuthenticationException e) {
System.out.println(身份验证失败!);
e.printStackTrace();
}
catch
(javax.naming.CommunicationException e) {
System.out.println(AD域连接失败!);
e.printStackTrace();
}
catch
(Exception e) {
System.out.println(身份验证未知异常!);
e.printStackTrace();
}
finally
{
if
(
null
!=ctx){
try
{
ctx.close();
ctx=
null
;
}
catch
(Exception e) {
e.printStackTrace();
}
}
}
}
public
static
void
main(String[] args) {
AdTest.connect(
10.10
.
2.116
,
389
, herman
@herman
.com,
123456
);
}
}
</string,string></string,string>
|
代码到此结束了,看看运行效果吧: