最近研究了jsp(SUN企業級應用的首選)中作HTTP認證的問題,它的工作方式如下:
1、server發送一個要求認證代碼401和一個頭信息WWW-authenticate,激發browser彈出一個認證窗口
2、server取得browser送來的認證頭"Authorization",它是加密的了,要用Base64方法解密,取得明文的用戶名和密碼
3、檢查用戶名和密碼,根據結果傳送不同的頁面
以下是jsp(SUN企業級應用的首選)的片斷,你也可以把它做成include文件。和Base64的加解密的class源碼。
如有興趣可與我聯系:[email protected]
<jsp(SUN企業級應用的首選):useBean id="base64"scope="page"class="Base64"/>
<%
if(request.getHeader("Authorization")==null){
response.setStatus(401);
response.setHeader("WWW-authenticate","Basic realm="unixboy.com"");
}else{
String encoded=(request.getHeader("Authorization"));
String tmp=encoded.substring(6);
String up=Base64.decode(tmp);
String user="";
String password="";
if(up!=null){
user=up.substring(0,up.indexOf(":"));
password=up.substring(up.indexOf(":")+1);
}
if(user.equals("unixboy")&&password.equals("123456")){
//認證成功
}else{
//認證失敗
}
}
%>
//消息加解密class
public class Base64
{
/** decode a Base 64 encoded String.
*<p><h4>String to byte conversion</h4>
* This method uses a naive String to byte interpretation, it simply gets each
* char of the String and calls it a byte.</p>
*<p>Since we should be dealing with Base64 encoded Strings that is a reasonable
* assumption.</p>
*<p><h4>End of data</h4>
* We dont try to stop the converion when we find the"="end of data padding char.
* We simply add zero bytes to the unencode buffer.</p>
*/
public static String decode(String encoded)
{
StringBuffer sb=new StringBuffer();
int maxturns;
//work out how long to loop for.
if(encoded.length()%3==0)