BASIC 認證:瀏覽器彈出原生登入對話框(如 Tomcat Manager)。
<%
response.addHeader("WWW-Authenticate", "Basic realm=\"Please Login\"");
response.sendError(401, "Unauthorized");
%>
String auth = request.getHeader("Authorization");
String authUser = "", authPass = "";
if (auth != null && auth.toUpperCase().startsWith("BASIC")) {
String encoded = auth.substring(6);
sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
String decoded = new String(dec.decodeBuffer(encoded));
String[] up = decoded.split(":", 2);
authUser = up[0]; authPass = up[1];
}
if (!"admin".equals(authUser) || !"password".equals(authPass)) {
response.setStatus(401);
response.setHeader("WWW-Authenticate", "Basic realm=\"My Realm\"");
} else {
// 驗證通過
}
解碼 Base64 後以冒號分割得帳號密碼,再進行比對。注意:sun.misc.BASE64Decoder 為內部 API,生產環境建議用 Apache Commons Codec。