1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package nginx.unit.websocket; 18 19 import java.nio.charset.Charset; 20 import java.nio.charset.StandardCharsets; 21 import java.util.Base64; 22 import java.util.Map; 23 24 /** 25 * Authenticator supporting the BASIC auth method. 26 */ 27 public class BasicAuthenticator extends Authenticator { 28 29 public static final String schemeName = "basic"; 30 public static final String charsetparam = "charset"; 31 32 @Override getAuthorization(String requestUri, String WWWAuthenticate, Map<String, Object> userProperties)33 public String getAuthorization(String requestUri, String WWWAuthenticate, 34 Map<String, Object> userProperties) throws AuthenticationException { 35 36 String userName = (String) userProperties.get(Constants.WS_AUTHENTICATION_USER_NAME); 37 String password = (String) userProperties.get(Constants.WS_AUTHENTICATION_PASSWORD); 38 39 if (userName == null || password == null) { 40 throw new AuthenticationException( 41 "Failed to perform Basic authentication due to missing user/password"); 42 } 43 44 Map<String, String> wwwAuthenticate = parseWWWAuthenticateHeader(WWWAuthenticate); 45 46 String userPass = userName + ":" + password; 47 Charset charset; 48 49 if (wwwAuthenticate.get(charsetparam) != null 50 && wwwAuthenticate.get(charsetparam).equalsIgnoreCase("UTF-8")) { 51 charset = StandardCharsets.UTF_8; 52 } else { 53 charset = StandardCharsets.ISO_8859_1; 54 } 55 56 String base64 = Base64.getEncoder().encodeToString(userPass.getBytes(charset)); 57 58 return " Basic " + base64; 59 } 60 61 @Override getSchemeName()62 public String getSchemeName() { 63 return schemeName; 64 } 65 66 } 67