1 /** 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 package org.apache.zookeeper.server.jersey.filters; 20 21 import java.io.IOException; 22 23 import javax.servlet.Filter; 24 import javax.servlet.FilterChain; 25 import javax.servlet.FilterConfig; 26 import javax.servlet.ServletException; 27 import javax.servlet.ServletRequest; 28 import javax.servlet.ServletResponse; 29 import javax.servlet.http.HttpServletRequest; 30 import javax.servlet.http.HttpServletResponse; 31 32 import org.apache.zookeeper.server.jersey.cfg.Credentials; 33 34 import com.sun.jersey.core.util.Base64; 35 36 public class HTTPBasicAuth implements Filter { 37 38 private Credentials credentials; 39 HTTPBasicAuth(Credentials c)40 public HTTPBasicAuth(Credentials c) { 41 credentials = c; 42 } 43 44 @Override doFilter(ServletRequest req0, ServletResponse resp0, FilterChain chain)45 public void doFilter(ServletRequest req0, ServletResponse resp0, 46 FilterChain chain) throws IOException, ServletException { 47 48 HttpServletRequest request = (HttpServletRequest) req0; 49 HttpServletResponse response = (HttpServletResponse) resp0; 50 51 String authorization = request.getHeader("Authorization"); 52 if (authorization != null) { 53 String c[] = parseAuthorization(authorization); 54 if (c != null && credentials.containsKey(c[0]) 55 && credentials.get(c[0]).equals(c[1])) { 56 chain.doFilter(request, response); 57 return; 58 } 59 } 60 61 response.setHeader("WWW-Authenticate", "Basic realm=\"Restricted\""); 62 response.sendError(401); 63 } 64 parseAuthorization(String authorization)65 private String[] parseAuthorization(String authorization) { 66 String parts[] = authorization.split(" "); 67 if (parts.length == 2 && parts[0].equalsIgnoreCase("Basic")) { 68 String userPass = Base64.base64Decode(parts[1]); 69 70 int p = userPass.indexOf(":"); 71 if (p != -1) { 72 return new String[] { userPass.substring(0, p), 73 userPass.substring(p + 1) }; 74 } 75 } 76 return null; 77 } 78 79 @Override init(FilterConfig arg0)80 public void init(FilterConfig arg0) throws ServletException { 81 } 82 83 @Override destroy()84 public void destroy() { 85 } 86 87 } 88