Http Basic认证就是访问的时候把用户名和密码用base64加密放在request的header的authorization中
服务端直接获取authorization,解析,跟用户名匹配即可。
用httpclient客户端的写法:
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
服务端(servlet):
String authorization = req.getHeader("authorization");
if(authorization==null||"".equals(authorization)){
resp.setStatus(401);
resp.setHeader("WWW-authenticate","Basic realm="请输入管理员密码"");
return;
}
String userandpass = new String(new BASE64Decoder().decodeBuffer(authorization.split(" ")[1]));
if(userandpass.split(":").length<2){
resp.setStatus(401);
resp.setHeader("WWW-authenticate","Basic realm="请输入管理员密码"");
return;
}
String user=userandpass.split(":")[0];
String pass=userandpass.split(":")[1];
if("cdv".equals(user)&&"0p-0p-0p-".equals(pass))
{
//true
//to do
}else{
resp.setStatus(401);
resp.setHeader("WWW-authenticate","Basic realm="请输入管理员密码"");
return;
}