1.简介:

时候浏览器会弹出一个登录验证的对话框,如下图,这就是使用HTTP基本认证。

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;

}

 

二. 补充:

basic authentication 格式:

Authorization: Basic YWRtaW46YWRtaW4= //笔者注释,Authorization: "Basic 用户名和密码的base64加密字符串"

客户端发送http请求
服务器发现配置了http auth,于是检查request里面有没有"Authorization"的http header
如果有,则判断Authorization里面的内容是否在用户列表里面,Authorization header的典型数据为"Authorization: Basic jdhaHY0=",其中Basic表示基础认证, jdhaHY0=是base64编码的"user:passwd"字符串。如果没有,或者用户密码不对,则返回http code 401页面给客户端

 

参考:

1.wiki:https://en.wikipedia.org/wiki/Basic_access_authentication

2.http://smalltalllong.iteye.com/blog/912046