http認證(一) - Basic 認證

文章主要講如何在tomcat中配置Basic認證以及工作流程:

[b]Tomcat配置:[/b]
1 在tomcat的webapps下新建一個目錄authen,再建立子目錄subdir,下面放一個index.jsp

2 在authen目錄下建立WEB-INF目錄,下放web.xml文件,內容如下

<security-constraint>
<web-resource-collection>
<web-resource-name>
My App
</web-resource-name>
<url-pattern>/subdir/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>test</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>BASIC</auth-method>
<realm-name>My Realm</realm-name>
</login-config>

3 在tomcat的tomcat-users.xml文件中添加一個用戶名密碼爲test,test的用戶,角色test。


[b]客戶端訪問:[/b]
訪問http://localhost:port/authen/subdir/index.jsp
會彈出對話框提示認證,輸入test test可以登錄。
[img]http://dl.iteye.com/upload/attachment/184068/d9bb95a9-5e35-304b-a8c1-b910a8b33a48.jpg[/img]

[b]工作流程(通過firebug可以查看請求頭)[/b]
1 客戶端先發請求(不知道要認證,頭裏不包含任何特殊信息)

2 服務器發一個401返回,並含有下面的頭
WWW-Authenticate Basic realm="My Realm"
[img]http://dl.iteye.com/upload/attachment/184072/aee4ad21-1db5-3723-8350-d8315c407ad9.jpg[/img]

3 客戶端認證,含有下面的頭
Authorization Basic dGVzdDp0ZXN0
“dGVzdDp0ZXN0”是"test:test"的Base64編碼。 (可以通過php函數base64_encode()驗證)
[img]http://dl.iteye.com/upload/attachment/184074/7396cfeb-826f-3d0d-88c9-b7bfe4fd8c4f.jpg[/img]

[b]缺點:[/b]
密碼明文傳輸,非常不安全。


[b]httpclient中的實現[/b]

查看org.apache.commons.httpclient.auth包的BasicScheme類

// Copy from the httpclient source code
// Omit some codes
public static String authenticate(UsernamePasswordCredentials credentials, String charset) {

...

StringBuffer buffer = new StringBuffer();
buffer.append(credentials.getUserName());
buffer.append(":");
buffer.append(credentials.getPassword());

return "Basic " + EncodingUtil.getAsciiString(Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset)));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章