当前位置: 首页 > 图文教程 > 网络编程 > JSP > 在jsp中作HTTP认证的方法

JSP
客户端界面中可视化的实现树形框架的设计
Win2000下JBoss开发环境配置
调试处理系统核心文件
Matrix java 大讲坛 之 可用性与人机界面
JMX调试----第三方工具使访问更加容易
用BSF如何在Java中嵌入javascript以及如何在javascript中
再次提醒\" 请不要做浮躁的人\"
从Coding Fan到真正的技术专家(cjsdn)
数据库BEAN:RESIN连接池
基于Java的Web服务器工作原理(一)
XDE中模式驱动的设计与开发(三)
页面流(Page flow)表单验证
高级页面流(Page flow):嵌套、异常处理和 Global.app
请不要做浮躁的人(ZT-必读)
解决日期选择问题,一劳永逸(使用Decorator模式实现日期选择组件)(二)
解决日期选择问题,一劳永逸(使用Decorator模式实现日期选择组件)(三)
解决日期选择问题,一劳永逸(使用Decorator模式实现日期选择组件)(四)
解决日期选择问题,一劳永逸(使用Decorator模式实现日期选择组件)(五)
EJB技术之旅(一)
MVC渐行渐进(二)

JSP 中的 在jsp中作HTTP认证的方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-02   浏览: 37 ::
收藏到网摘: n/a

 

    最近研究了jsp中作HTTP认证的问题,它的工作方式如下:

1、server发送一个要求认证代码401和一个头信息WWW-authenticate,激发browser弹出一个认证窗口

2、server取得browser送来的认证头"Authorization",它是加密的了,要用Base64方法解密,取得明文的用户名和密码

3、检查用户名和密码,根据结果传送不同的页面


以下是jsp的片断,你也可以把它做成include文件。和Base64的加解密的class源码。
如有兴趣可与我联系:[email protected]

<jsp: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 don''t 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)
                maxturns=encoded.length();
                else
                maxturns=encoded.length()+(3-(encoded.length()%3));
                //tells us whether to include the char in the unencode
                boolean skip;
                //the unencode buffer
                byte[] unenc=new byte[4];
   &n"