| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

FilterでBasic認証を実装

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

FilterでBasic認証を実装

Java |

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;

import javax.mail.internet.MimeUtility;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BasicAuthenticationFilter implements Filter {
    /**
     * レルム名
     */
    private final String realmName = "hoge";

    /* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */
    public void doFilter(ServletRequest request, 
                         ServletResponse response, 
                         FilterChain filterChain) throws IOException, ServletException {
        
        ByteArrayInputStream bin = null;
        BufferedReader br = null;
        try {
            HttpServletRequest httpReq = (HttpServletRequest)request;
            
            String basicAuthData = httpReq.getHeader("authorization");

            // Basic認証から情報を取得
            String basicAuthBody = basicAuthData.substring(6); // ex 'Basic dG9tY2F0OnRvbWNhdA== ' 
            bin = new ByteArrayInputStream(basicAuthBody.getBytes()); 
            br = new BufferedReader(
                    new InputStreamReader(MimeUtility.decode(bin,"base64")));

            StringBuilder buf = new StringBuilder();
            String line = null;
            while ((line = br.readLine())!=null) {
                buf.append(line);
            }
            String[] loginInfo = buf.toString().split(":");
            String username = CollectionUtil.safeArrayElement(loginInfo,0,"");
            String password = CollectionUtil.safeArrayElement(loginInfo,1,"");

            boolean isAuthorized = /* username password を利用して認証を実施 */
            
            if (!isAuthorized) {
                //ブラウザに UnAuthorizedエラー(401)を返す
                HttpServletResponse httpRes = (HttpServletResponse)response;
                httpRes.setHeader("WWW-Authenticate","Basic realm=" + this.realmName);
                httpRes.setContentType("text/html");
                httpRes.sendError(HttpServletResponse.SC_UNAUTHORIZED); // 401
            } else {
                filterChain.doFilter(request, response);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            try {
                if (bin!=null) bin.close();
                if (br !=null) br.close();
            } catch(Exception e) {}
        }
    }
}