1 | /** |
2 | * Licensed to jclouds, Inc. (jclouds) under one or more |
3 | * contributor license agreements. See the NOTICE file |
4 | * distributed with this work for additional information |
5 | * regarding copyright ownership. jclouds 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, |
13 | * software distributed under the License is distributed on an |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
15 | * KIND, either express or implied. See the License for the |
16 | * specific language governing permissions and limitations |
17 | * under the License. |
18 | */ |
19 | package org.jclouds.http.filters; |
20 | |
21 | import static com.google.common.base.Preconditions.checkNotNull; |
22 | import static org.jclouds.Constants.PROPERTY_CREDENTIAL; |
23 | import static org.jclouds.Constants.PROPERTY_IDENTITY; |
24 | |
25 | import java.io.UnsupportedEncodingException; |
26 | |
27 | import javax.inject.Inject; |
28 | import javax.inject.Named; |
29 | import javax.inject.Singleton; |
30 | import javax.ws.rs.core.HttpHeaders; |
31 | |
32 | import org.jclouds.crypto.Crypto; |
33 | import org.jclouds.crypto.CryptoStreams; |
34 | import org.jclouds.http.HttpException; |
35 | import org.jclouds.http.HttpRequest; |
36 | import org.jclouds.http.HttpRequestFilter; |
37 | import org.jclouds.http.utils.ModifyRequest; |
38 | |
39 | /** |
40 | * Uses Basic Authentication to sign the request. |
41 | * |
42 | * @see <a href= "http://en.wikipedia.org/wiki/Basic_access_authentication" /> |
43 | * @author Adrian Cole |
44 | * |
45 | */ |
46 | @Singleton |
47 | public class BasicAuthentication implements HttpRequestFilter { |
48 | |
49 | private final String header; |
50 | |
51 | @Inject |
52 | public BasicAuthentication(@Named(PROPERTY_IDENTITY) String user, @Named(PROPERTY_CREDENTIAL) String password, |
53 | Crypto crypto) throws UnsupportedEncodingException { |
54 | this.header = "Basic " |
55 | + CryptoStreams.base64(String.format("%s:%s", checkNotNull(user, "user"), |
56 | checkNotNull(password, "password")).getBytes("UTF-8")); |
57 | } |
58 | |
59 | @Override |
60 | public HttpRequest filter(HttpRequest request) throws HttpException { |
61 | return ModifyRequest.replaceHeader(request, HttpHeaders.AUTHORIZATION, header); |
62 | } |
63 | } |