声明式为开发者带来了很多很多好处,其中有一点就是开发者不必在JSP或者servlet中加入任何安全代码,完全由容器负责。但是,正是由于这种便利,它需要付出一定的代价:它需要一个服务器特定的组件,设置用户名、密码和角色方法并不标准,因此不容易移植到其他的服务器上,因此,有时候我们需要通过编程式安全只是让servlet或者JSP页面使用用户名和密码机制,做到与容器无关。
在相关页面的servlet请求中 doGet方法中
(1)检查是否Authorization请求头,如果没有跳至第5步
String authorization = request.getHeader(“Authorization”);
if( authorization == null )
{
askForPassword(response)
};
(2)获取加密后的用户名和密码字符串(格式:Authorization:Basic encodeDate;)
String userInfo = authorization.subString(6).trim();
(3)转换base64格式的用户名/密码
Base64Decoder decoder = new BaseDecoder();
String nameandpassword = new String(decoder.decodeBuffer(userInfo));
Int index = nameandpassword.indexOf(“:”);
String user=nameandpassword.substring(0,index);
String password = nameandpassword.substring(index+1);
(4)验证用户名和密码,调用数据库去判断 (5)如果身份验证失败,则向客户端返回特定的响应
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//HTTP 401
response.setHeader(“WWW-Authenticate”,”BASIC realm=\”Insider-Trading\””);