1.简介:
时候浏览器会弹出一个登录验证的对话框,如下图,这就是使用HTTP基本认证。
下面来看看一看这个认证的工作过程:
第一步: 客户端发送http request 给服务器,服务器验证该用户是否已经登录验证过了,如果没有的话,
服务器会返回一个401 Unauthozied给客户端,并且在Response 的 header "WWW-Authenticate" 中添加信息。
2.实现
需要下载浏览器插件实现发送认证头,推荐POSTMAN Launcher
3.java code:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String authorization = request.getHeader("Authorization"); logger.info("Authorization is [{}]", authorization); if (authorization!=null&&authorization.split(" ").length == 2) { String userAndPass = new String(new BASE64Decoder().decodeBuffer(authorization.split(" ")[1])); String user = userAndPass.split(":").length == 2 ? userAndPass.split(":")[0] : null; String pass = userAndPass.split(":").length == 2 ? userAndPass.split(":")[1] : null; logger.info("Username is [{}],Password is [{}]", user, pass); } return true; }
参考:
1.wiki:https://en.wikipedia.org/wiki/Basic_access_authentication
2.http://smalltalllong.iteye.com/blog/912046
3.http://blog.csdn.net/kkdelta/article/details/28419625