Borrowing materials: "The principle and implementation of HTTP using Basic Authentication"
Look at the HTTP protocol original book, the third part of the 11th chapter identification, authentication and security, when the cookie is disabled can use 401 status code and response to the head www-authenticate. Cookies are disabled, one is the service is not available, remind the user to turn on the cookie function, such as NetEase 163 mailbox is so dry; the other is URL rewriting, The Response.encodeurl method in Java automatically determines whether the client disables the cookie and then appends the option Jsessionid to main after the URL, but the encoding is cumbersome.
Small website can use 401 status code and response header www-authenticate to do it, play it, but it's not safe in this way ... Base64 is too easy to be cracked.
In addition, it is necessary to know that at the time of the first certification, the initial response is not a complete response header; After authentication, the browser will be in the session between the surviving, each request with the request header authorization, as follows.
Package Cn.wxy.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.sun.org.apache.xerces.internal.impl.dv.util.Base64, @WebServlet ("/auth") public class Authservlet extends HttpServlet {private static final long serialversionuid = 1l;protected void doget (HttpServletRequest request, HttpServlet Response Response) throws Servletexception, IOException {request.setcharacterencoding ("UTF-8"); Response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8"); String auth = Request.getheader ("Authorization"), if (Hasauth (auth, response)) {auth = new String (Base64.decode ( Auth.split ("") [1]); System.out.println (auth);/** * for verification: output * Before decoding: Basic Emhhbmdzyw46mtiz * decoding: zhangsan:123 (Username:password) */}} protected void DoPost (HttpServletRequest request, HttpServletResponse ResponSE) throws Servletexception, IOException {doget (request, response);} /** * for verifying that the request header contains authorization information * to know more about 401 verification, please see Request.getauthtype () * @param auth * @param response * @return */priv Ate boolean Hasauth (String auth, httpservletresponse response) {if (auth = null | | Auth.trim (). Equals ("")) { Response.setstatus (401); Response.setheader ("Www-authenticate", "Basic realm=\" localhost\ ""); return false;} return true;}}
Note:
On a whim, I looked at 401 head
"http" http 401Basic authentication and www-authenticate, Authorization