bc486f4deacde0ebf873cbbf8c016f4c234cd937
[ccsdk/features.git] /
1 /*\r
2  * Copyright © 2017-2018 AT&T Intellectual Property.\r
3  * \r
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except\r
5  * in compliance with the License. You may obtain a copy of the License at\r
6  * \r
7  * http://www.apache.org/licenses/LICENSE-2.0\r
8  * \r
9  * Unless required by applicable law or agreed to in writing, software distributed under the License\r
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r
11  * or implied. See the License for the specific language governing permissions and limitations under\r
12  * the License.\r
13  */\r
14 \r
15 package org.onap.ccsdk.config.rest.adaptor.utils;\r
16 \r
17 import java.io.IOException;\r
18 import java.nio.charset.Charset;\r
19 import org.springframework.http.HttpRequest;\r
20 import org.springframework.http.client.ClientHttpRequestExecution;\r
21 import org.springframework.http.client.ClientHttpRequestInterceptor;\r
22 import org.springframework.http.client.ClientHttpResponse;\r
23 import org.springframework.util.Assert;\r
24 import org.springframework.util.Base64Utils;\r
25 \r
26 public class BasicAuthorizationInterceptor implements ClientHttpRequestInterceptor {\r
27     private static final Charset UTF_8 = Charset.forName("UTF-8");\r
28     \r
29     private final String username;\r
30     \r
31     private final String pass;\r
32     \r
33     /**\r
34      * Create a new interceptor which adds a BASIC authorization header for the given username and pass.\r
35      *\r
36      * @param username the username to use\r
37      * @param pass the password to use\r
38      */\r
39     public BasicAuthorizationInterceptor(String username, String pass) {\r
40         Assert.hasLength(username, "Username must not be empty");\r
41         this.username = username;\r
42         this.pass = (pass != null ? pass : "");\r
43     }\r
44     \r
45     @Override\r
46     public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)\r
47             throws IOException {\r
48         \r
49         String token = Base64Utils.encodeToString((this.username + ":" + this.pass).getBytes(UTF_8));\r
50         request.getHeaders().add("Authorization", "Basic " + token);\r
51         return execution.execute(request, body);\r
52     }\r
53 }\r