這就是第三方驗證。一般有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>
|
代碼到此結束了,看看運行效果吧:
