Data and personal practice summary of JSP basic form verification

Source: Internet
Author: User
Tags auth split

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.