xref: /unit/src/java/nginx/unit/websocket/Authenticator.java (revision 1157:7ae152bda303)
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.util.HashMap;
20 import java.util.Map;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23 
24 /**
25  * Base class for the authentication methods used by the websocket client.
26  */
27 public abstract class Authenticator {
28     private static final Pattern pattern = Pattern
29             .compile("(\\w+)\\s*=\\s*(\"([^\"]+)\"|([^,=\"]+))\\s*,?");
30 
31     /**
32      * Generate the authentication header that will be sent to the server.
33      * @param requestUri The request URI
34      * @param WWWAuthenticate The server auth challenge
35      * @param UserProperties The user information
36      * @return The auth header
37      * @throws AuthenticationException When an error occurs
38      */
getAuthorization(String requestUri, String WWWAuthenticate, Map<String, Object> UserProperties)39     public abstract String getAuthorization(String requestUri, String WWWAuthenticate,
40             Map<String, Object> UserProperties) throws AuthenticationException;
41 
42     /**
43      * Get the authentication method.
44      * @return the auth scheme
45      */
getSchemeName()46     public abstract String getSchemeName();
47 
48     /**
49      * Utility method to parse the authentication header.
50      * @param WWWAuthenticate The server auth challenge
51      * @return the parsed header
52      */
parseWWWAuthenticateHeader(String WWWAuthenticate)53     public Map<String, String> parseWWWAuthenticateHeader(String WWWAuthenticate) {
54 
55         Matcher m = pattern.matcher(WWWAuthenticate);
56         Map<String, String> challenge = new HashMap<>();
57 
58         while (m.find()) {
59             String key = m.group(1);
60             String qtedValue = m.group(3);
61             String value = m.group(4);
62 
63             challenge.put(key, qtedValue != null ? qtedValue : value);
64 
65         }
66 
67         return challenge;
68 
69     }
70 
71 }
72