Http認證之Basic認證
阿新 • • 發佈:2019-02-11
文章主要講如何在tomcat中配置Basic認證以及工作流程:
Tomcat配置:
1 在tomcat的webapps下新建一個目錄authen,再建立子目錄subdir,下面放一個index.jsp
2 在authen目錄下建立WEB-INF目錄,下放web.xml檔案,內容如下
Xml程式碼
3 在tomcat的tomcat-users.xml檔案中新增一個使用者名稱密碼為test,test的使用者,角色test。
客戶端訪問:
訪問http://localhost:port/authen/subdir/index.jsp
會彈出對話方塊提示認證,輸入test test可以登入。
工作流程(通過firebug可以檢視請求頭)
1 客戶端先發請求(不知道要認證,頭裡不包含任何特殊資訊)
2 伺服器發一個401返回,並含有下面的頭
WWW-Authenticate Basic realm="My Realm"
3 客戶端認證,含有下面的頭
Authorization Basic dGVzdDp0ZXN0
“dGVzdDp0ZXN0”是"test:test"的Base64編碼。 (可以通過php函式base64_encode()驗證)
缺點:
密碼明文傳輸,非常不安全。
httpclient中的實現
Java程式碼
Tomcat配置:
1 在tomcat的webapps下新建一個目錄authen,再建立子目錄subdir,下面放一個index.jsp
2 在authen目錄下建立WEB-INF目錄,下放web.xml檔案,內容如下
Xml程式碼
- <security-constraint>
- <web-resource-collection>
- <web-resource-name>
- My App
- </web-resource-name>
- <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。
客戶端訪問:
訪問http://localhost:port/authen/subdir/index.jsp
會彈出對話方塊提示認證,輸入test test可以登入。
工作流程(通過firebug可以檢視請求頭)
1 客戶端先發請求(不知道要認證,頭裡不包含任何特殊資訊)
2 伺服器發一個401返回,並含有下面的頭
WWW-Authenticate Basic realm="My Realm"
3 客戶端認證,含有下面的頭
Authorization Basic dGVzdDp0ZXN0
“dGVzdDp0ZXN0”是"test:test"的Base64編碼。 (可以通過php函式base64_encode()驗證)
缺點:
密碼明文傳輸,非常不安全。
httpclient中的實現
Java程式碼
- 檢視org.apache.commons.httpclient.auth包的BasicScheme類
- // Copy from the httpclient source code
- // Omit some codes
- publicstatic 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)));
- }