[[Java]] | [[Category:コード片]]
import java.io.Buffered[[R]]eaderBufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream[[R]]eaderInputStreamReader;
import java.util.Enumeration;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.Servlet[[R]]equestServletRequest; import javax.servlet.Servlet[[R]]esponseServletResponse; import javax.servlet.http.HttpServlet[[R]]equestHttpServletRequest; import javax.servlet.http.HttpServlet[[R]]esponseHttpServletResponse;
public class BasicAuthenticationFilter implements Filter {
private final String realmName = "hoge";
/* @see javax.servlet.Filter#doFilter(javax.servlet.Servlet[[R]]equestServletRequest, javax.servlet.Servlet[[R]]esponseServletResponse, javax.servlet.FilterChain) */ public void doFilter(Servlet[[R]]equest ServletRequest request, Servlet[[R]]esponse ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
ByteArrayInputStream bin = null;
Buffered[[R]]eader BufferedReader br = null;
try {
HttpServlet[[R]]equest http[[R]]eq HttpServletRequest httpReq = (HttpServlet[[R]]equestHttpServletRequest)request;
String basicAuthData = httpReq.get[[Header]]("authorization");
// Basic認証から情報を取得
String basicAuthBody = basicAuthData.substring(6); // ex 'Basic dG9tY2F0On[[R]]vbWNhdAdG9tY2F0OnRvbWNhdA== '
bin = new ByteArrayInputStream(basicAuthBody.getBytes());
br = new Buffered[[R]]eaderBufferedReader( new InputStream[[R]]eaderInputStreamReader(MimeUtility.decode(bin,"base64")));
StringBuilder buf = new StringBuilder();
if (!isAuthorized) {
//ブラウザに UnAuthorizedエラー(401)を返す
HttpServlet[[R]]esponse http[[R]]es HttpServletResponse httpRes = (HttpServlet[[R]]esponseHttpServletResponse)response;
httpRes.set[[Header]]("WWW-Authenticate","Basic realm=" + this.realmName);
http[[R]]eshttpRes.setContentType("text/html"); http[[R]]eshttpRes.sendError(HttpServlet[[R]]esponseHttpServletResponse.SC_UNAUTHO[[R]]IZEDSC_UNAUTHORIZED); // 401
} else {
filterChain.doFilter(request, response);