检查HTTP 的 Basic认证代码示例-JSP

检查HTTP 的 Basic认证. since http1.0

代码如下所示:

<%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" %>
<%@ page import="sun.misc.BASE64Decoder" %>
<%@ page import="java.io.IOException" %>
<%!
    // 检查HTTP 的 Basic认证. since http1.0
    public static boolean checkAuth(HttpServletRequest request, String id, String pwd){
        boolean authOK = false;
        // 认证后每次HTTP请求都会附带上 Authorization 头信息
        String Authorization = request.getHeader("Authorization");
        if(null == Authorization || Authorization.trim().isEmpty()){
            // 需要认证
            return authOK;
        }
        //
        String[] basicArray = Authorization.split("\\s+");
        if(null == basicArray || 2 != basicArray.length){
            return authOK;
        }
        //
        String basic = basicArray[0];
        String base64 = basicArray[1];
        //
        try {
            byte[] buf = new BASE64Decoder().decodeBuffer(base64);
            String idpass = new String(buf, "UTF-8");
            if(null == idpass || idpass.trim().isEmpty()){
                // 需要认证
                return authOK;
            }
            //
            String[] idpassArray = idpass.split(":");
            if(null == idpassArray || 2 != idpassArray.length){
                return authOK;
            }
            String _id = idpassArray[0];
            String _pass = idpassArray[1];
            //
            if(id.equalsIgnoreCase(_id) && pwd.equalsIgnoreCase(_pass)){
                authOK = true;// 认证成功
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //
        return authOK;
    }

    // 不依赖 this 状态的方法,其实都应该设置为 static
    public static void requireAuth(HttpServletResponse response, String msg){
        // 发送状态码 401, 不能使用 sendError,坑
        response.setStatus(401,"Authentication Required");
        // 发送要求输入认证信息,则浏览器会弹出输入框
        response.addHeader("WWW-Authenticate","Basic realm="+ msg);
        return;
    }
%>
<%
    //
    String Authorization = request.getHeader("Authorization");
    //
    String userid = "admin";
    String pwd = "11111111";
    boolean authOK = checkAuth(request, userid, pwd);
    //
    if (!authOK) {
		// 如果认证失败,则要求认证
        requireAuth(response, "R U OK,小米");
        return;
    }
%>
<html>
<head>
    <title>R U OK?</title>
</head>
<body>
    R U OK? <%=userid %>. Your Password is <%="********"%>
</body>
</html>

请参考代码中的注释,具体信息,还可以参考《图解HTTP》。我看着这本书中的HTTP-Basic认证手痒,就写了这么一个demo代码。



上一篇:WebDriver-自动化测试利器剖析


下一篇:linux下命令源码