答案:最近研究了jsp中作HTTP认证的问题,它的工作方式如下:<br>
<br>
1、server发送一个要求认证代码401和一个头信息WWW-authenticate,激发browser弹出一个认证窗口<br>
<br>
2、server取得browser送来的认证头"Authorization",它是加密的了,要用Base64方法解密,取得明文的用户名和密码<br>
<br>
3、检查用户名和密码,根据结果传送不同的页面<br>
<br>
<br>
以下是jsp的片断,你也可以把它做成include文件。和Base64的加解密的class源码。<br>
如有兴趣可与我联系:unixboy@yeah.net<br>
<br>
<jsp:useBean id="base64" scope="page" class="Base64"/><br>
<%<br>
if(request.getHeader("Authorization")==null){<br>
response.setStatus(401);<br>
response.setHeader("WWW-authenticate", "Basic realm=\"unixboy.com\"");<br>
}else{<br>
String encoded=(request.getHeader("Authorization"));<br>
String tmp=encoded.substring(6);<br>
String up=Base64.decode(tmp);<br>
String user="";<br>
String password="";<br>
if(up!=null){<br>
user=up.substring(0,up.indexOf(":"));<br>
password=up.substring(up.indexOf(":")+1);<br>
}<br>
if(user.equals("unixboy")&&password.equals("123456")){<br>
//认证成功<br>
}else{<br>
//认证失败<br>
}<br>
}<br>
%><br>
<br>
<br>
//消息加解密class<br>
public class Base64<br>
{<br>
/** decode a Base 64 encoded String.<br>
* <p><h4>String to byte conversion</h4><br>
* This method uses a 易做图 String to byte interpretation, it simply gets each<br>
* char of the String and calls it a byte.</p><br>
* <p>Since we should be dealing with Base64 encoded Strings that is a reasonable<br>
* assumption.</p><br>
* <p><h4>End of data</h4><br>
* We don't try to stop the converion when we find the "=" end of data padding char.<br>
* We simply add zero bytes to the unencode buffer.</p><br>
*/<br>
public static String decode(String encoded)<br>
{<br>
StringBuffer sb=new StringBuffer();<br>
int maxturns;<br>
//work out how long to loop for.<br>
if(encoded.length()%3==0)<br>
maxturns=encoded.length();<br>
else<br>
maxturns=encoded.length()+(3-(encoded.length()%3));<br>
//tells us whether to include the char in the unencode<br>
boolean skip;<br>
//the unencode buffer<br>
byte[] unenc=new byte[4];<br>
byte b;<br>
for(int i=0,j=0; i<maxturns; i++)<br>
{<br>
skip=false;<br>
//get the byte to convert or 0<br>
if(i<encoded.length())
上一个:JavaServer Pages (JSP) 1.0简单介绍 ---III
下一个:Orion下自定义Tag