What is basic validation? Readers will often see such a login interface (IE):
For example, Tomcat's manager application: Http://localhost:8080/mananager is the way to log in.
OK, first look at the following JSP code, the reader Test yourself:
<%
response.addHeader("WWW-Authenticate", "Basic realm="Please Login"");
response.sendError(401, "Unauthorized");
%>
See, a similar dialog box pops up.
The following code directly copy php/jsp/asp to achieve basic verification of the content of the article:
JSP is not so simple, you need to first get [i]authorization[/i] head, and then intercept the user name, password section, the Base64 decoding, and finally use the colon ":" Split string, respectively, after decoding the user name, password to verify the comparison:
Here's the code:
// 进行 HTTP 验证 (Basic Authorization)
String auth_user = "", auth_pass = "";
String auth = request.getHeader("Authorization");
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[] userAndPass = decoded.split(":", 2);
auth_user = userAndPass[0];
auth_pass = userAndPass[1];
} //end if
if (!auth_user.equals("admin") || !auth_pass.equals("password")) {
// 帐号或密码不正确,无法通过验证!
response.setStatus(401);
response.setHeader("WWW-Authenticate", "Basic realm="My Realm"");
} else {
// 验证通过,可以进行其他业务操作了
} //end if