1. 程式人生 > >Http認證之Basic認證

Http認證之Basic認證

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

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

2 在authen目錄下建立WEB-INF目錄,下放web.xml檔案,內容如下
Xml程式碼 複製程式碼 收藏程式碼
  1. <security-constraint>
  2.     <web-resource-collection>
  3.         <web-resource-name>
  4.             My App  
  5.         </web-resource-name>
  6.         <url-pattern>
    /subdir/*</url-pattern>
  7.     </web-resource-collection>
  8.     <auth-constraint>
  9.         <role-name>test</role-name>
  10.     </auth-constraint>
  11. </security-constraint>
  12. <login-config>
  13.     <auth-method>BASIC</auth-method>
  14.     <realm-name>My Realm</realm-name>
  15. </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程式碼 複製程式碼 收藏程式碼
  1. 檢視org.apache.commons.httpclient.auth包的BasicScheme類  
  2.     // Copy from the httpclient source code
  3.     // Omit some codes
  4.     publicstatic String authenticate(UsernamePasswordCredentials credentials, String charset) {  
  5.         ...  
  6.         StringBuffer buffer = new StringBuffer();  
  7.         buffer.append(credentials.getUserName());  
  8.         buffer.append(":");  
  9.         buffer.append(credentials.getPassword());  
  10.         return"Basic " + EncodingUtil.getAsciiString(Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset)));  
  11.     }