WEB應(yīng)用中的身份驗(yàn)證(1)--基本身份驗(yàn)證BASIC authorization method
Posted on 2011-03-22 18:33 瘋狂 閱讀(1782) 評(píng)論(0) 編輯 收藏 所屬分類: java 、java安全在任何一種WEB應(yīng)用開(kāi)發(fā)中,不論大中小規(guī)模的,每個(gè)開(kāi)發(fā)者都會(huì)遇到一些需要保護(hù)程序數(shù)據(jù)的問(wèn)題,涉及到用戶的LOGIN ID和PASSWORD。那么如何執(zhí)行驗(yàn)證方式更好呢?實(shí)際上,有很多方式來(lái)實(shí)現(xiàn)。在本文里,我們不會(huì)把所有的驗(yàn)證方法都考慮到,我們的目的是讓你學(xué)會(huì)如何以最簡(jiǎn)單最方便的驗(yàn)證方法來(lái)完成。下面將討論基本驗(yàn)證方式之一(BASIC authorization method)
要搭建整個(gè)流程需要四個(gè)階段:
一、建立測(cè)試用數(shù)據(jù)庫(kù)
我們這里用Mysql進(jìn)行測(cè)試,其他數(shù)據(jù)庫(kù)完全一樣。
1、創(chuàng)建用戶表
CREATE TABLE users (
id int(11) NOT NULL auto_increment,
username varchar(20) NOT NULL,
password varchar(20) NOT NULL,
PRIMARY KEY (id)
)
2、創(chuàng)建權(quán)限表(此事例中用不到)
CREATE TABLE roles(
id int(11) NOT NULL auto_increment,
rolename varchar(20) NOT NULL,
PRIMARY KEY (id)
)
3、創(chuàng)建用戶-權(quán)限對(duì)應(yīng)表
CREATE TABLE user_roles (
id int(11) NOT NULL auto_increment,
username varchar(20) NOT NULL,
rolename varchar(20) NOT NULL,
PRIMARY KEY (id)
)
4、插入數(shù)據(jù)
insert into users(username,password) values('zhangdongyu', 'loveyuanyuan')
insert into roles(rolename) values('manager')
insert into user_roles(username,rolename) values('zhangdongyu', 'manager')
二、修改${tomcat}\conf\server.xml
找到
<!--
<Realm className="org.apache.catalina.realm.MemoryRealm" />
-->
在上面這句話下面添加一下內(nèi)容:
<Realm
className="org.apache.catalina.realm.JDBCRealm"
debug="99"
driverName="org.gjt.mm.mysql.Driver"
connectionURL="jdbc:mysql://localhost/weblogin" <!--數(shù)據(jù)庫(kù)連接地址-->
connectionName="root" <!--數(shù)據(jù)庫(kù)用戶名-->
connectionPassword="123" <!--數(shù)據(jù)庫(kù)密碼-->
userTable="users" <!--用戶表-->
userNameCol="username" <!--用戶名列-->
userCredCol="password" <!--密碼列-->
userRoleTable="user_roles" <!--用戶權(quán)限對(duì)應(yīng)表-->
roleNameCol="rolename" <!--權(quán)限列-->
/>
三、創(chuàng)建工程
在Eclipse創(chuàng)建一個(gè)web工程sercurityTest,在WebRoot下面創(chuàng)建一個(gè)文件夾admin(也可在里面建立幾個(gè)文件)
在web.xml文件中添加以下片段:
<security-constraint>
<web-resource-collection>
<web-resource-name>Web Demo</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>manager</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Web Demo</realm-name>
</login-config>
四、重啟Tomcat,使設(shè)置生效
總結(jié)測(cè)試:
通過(guò)上面的四部分配置,當(dāng)你再次訪問(wèn)程序中受保護(hù)的地址,如:http://localhost/sercurityTest/admin時(shí)
會(huì)彈出驗(yàn)證對(duì)話框,讓你輸入用戶名和密碼,只有輸入庫(kù)中的用戶名密碼并且該用戶有manager權(quán)限時(shí)才能進(jìn)
入受保護(hù)目錄。
轉(zhuǎn)載自:http://blog.csdn.net/swengineer/archive/2006/12/01/1424020.aspx