HTTP基本认证
0
以前就挺好奇路由器认证时的弹窗是怎么做的。今天看了HTTP权威指南的HTTP基本认证基本上了解了。这里放一个JSP的示例,更多资料可以看HTTP权威指南的基本认证机制章节,或者参考后面的文章。
<%@page import="org.apache.http.HttpStatus"%>
<%@page import="org.apache.http.HttpHeaders"%>
<%@page import="org.apache.commons.codec.binary.Base64"%>
<%@page import="org.jboss.netty.handler.codec.base64.Base64Decoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
boolean auth = false;
String pswd = request.getHeader(HttpHeaders.AUTHORIZATION);
if(pswd != null && pswd.length() > 6) {
pswd = pswd.substring(6);
pswd = new String(Base64.decodeBase64(pswd));
if(pswd.equals("root:root")) {
auth = true;
}
}
if(!auth) {
response.setStatus(HttpStatus.SC_UNAUTHORIZED);
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic Realm=\"acgist\"");
}
%>
<!DOCTYPE html>
<html>
<head>
<title>授权测试</title>
</head>
<body>
</body>
</html>