==[[FilterでBasic認証を実装]]==[[Java]] | {{category [[Category:コード片}}]]
import java.io.BufferedReaderBuffered[[R]]eader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReaderInputStream[[R]]eader;
import java.util.Enumeration;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestServlet[[R]]equest; import javax.servlet.ServletResponseServlet[[R]]esponse; import javax.servlet.http.HttpServletRequestHttpServlet[[R]]equest; import javax.servlet.http.HttpServletResponseHttpServlet[[R]]esponse;
public class BasicAuthenticationFilter implements Filter {
private final String realmName = "hoge";
/* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequestServlet[[R]]equest, javax.servlet.ServletResponseServlet[[R]]esponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest Servlet[[R]]equest request, ServletResponse Servlet[[R]]esponse response,
FilterChain filterChain) throws IOException, ServletException {
ByteArrayInputStream bin = null;
BufferedReader Buffered[[R]]eader br = null;
try {
HttpServletRequest httpReq HttpServlet[[R]]equest http[[R]]eq = (HttpServletRequestHttpServlet[[R]]equest)request;
String basicAuthData = httpReq.getHeaderget[[Header]]("authorization");
// Basic認証から情報を取得
String basicAuthBody = basicAuthData.substring(6); // ex 'Basic dG9tY2F0OnRvbWNhdAdG9tY2F0On[[R]]vbWNhdA== '
bin = new ByteArrayInputStream(basicAuthBody.getBytes());
br = new BufferedReaderBuffered[[R]]eader( new InputStreamReaderInputStream[[R]]eader(MimeUtility.decode(bin,"base64")));
StringBuilder buf = new StringBuilder();
if (!isAuthorized) {
//ブラウザに UnAuthorizedエラー(401)を返す
HttpServletResponse httpRes HttpServlet[[R]]esponse http[[R]]es = (HttpServletResponseHttpServlet[[R]]esponse)response; httpRes.setHeaderset[[Header]]("WWW-Authenticate","Basic realm=" + this.realmName); httpReshttp[[R]]es.setContentType("text/html"); httpReshttp[[R]]es.sendError(HttpServletResponseHttpServlet[[R]]esponse.SC_UNAUTHORIZEDSC_UNAUTHO[[R]]IZED); // 401
} else {
filterChain.doFilter(request, response);