001/*
002 * oauth2-oidc-sdk
003 *
004 * Copyright 2012-2016, Connect2id Ltd and contributors.
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
007 * this file except in compliance with the License. You may obtain a copy of the
008 * License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software distributed
013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
015 * specific language governing permissions and limitations under the License.
016 */
017
018package com.nimbusds.oauth2.sdk.auth;
019
020
021import java.io.UnsupportedEncodingException;
022import java.net.URLDecoder;
023import java.net.URLEncoder;
024import java.nio.charset.Charset;
025import java.nio.charset.StandardCharsets;
026import java.util.Collections;
027import java.util.Set;
028
029import net.jcip.annotations.Immutable;
030
031import com.nimbusds.jose.util.Base64;
032import com.nimbusds.oauth2.sdk.ParseException;
033import com.nimbusds.oauth2.sdk.http.HTTPRequest;
034import com.nimbusds.oauth2.sdk.id.ClientID;
035
036
037/**
038 * Client secret basic authentication at the Token endpoint. Implements
039 * {@link ClientAuthenticationMethod#CLIENT_SECRET_BASIC}.
040 *
041 * <p>Example HTTP Authorization header (for client identifier "s6BhdRkqt3" and
042 * secret "7Fjfp0ZBr1KtDRbnfVdmIw"):
043 *
044 * <pre>
045 * Authorization: Basic czZCaGRSa3F0Mzo3RmpmcDBaQnIxS3REUmJuZlZkbUl3
046 * </pre>
047 *
048 * <p>Related specifications:
049 *
050 * <ul>
051 *     <li>OAuth 2.0 (RFC 6749), sections 2.3.1 and 3.2.1.
052 *     <li>OpenID Connect Core 1.0, section 9.
053 *     <li>HTTP Authentication: Basic and Digest Access Authentication 
054 *         (RFC 2617).
055 * </ul>
056 */
057@Immutable
058public final class ClientSecretBasic extends PlainClientSecret {
059
060
061        /**
062         * The default character set for the client ID and secret encoding.
063         */
064        private static final Charset UTF8_CHARSET = StandardCharsets.UTF_8;
065        
066        
067        /**
068         * Creates a new client secret basic authentication.
069         *
070         * @param clientID The client identifier. Must not be {@code null}.
071         * @param secret   The client secret. Must not be {@code null}.
072         */
073        public ClientSecretBasic(final ClientID clientID, final Secret secret) {
074        
075                super(ClientAuthenticationMethod.CLIENT_SECRET_BASIC, clientID, secret);
076        }
077        
078        
079        @Override
080        public Set<String> getFormParameterNames() {
081                
082                return Collections.emptySet();
083        }
084        
085        
086        /**
087         * Returns the HTTP Authorization header representation of this client
088         * secret basic authentication.
089         *
090         * <p>Note that OAuth 2.0 (RFC 6749, section 2.3.1) requires the client
091         * ID and secret to be {@code application/x-www-form-urlencoded} before
092         * passing them to the HTTP basic authentication algorithm. This
093         * behaviour differs from the original HTTP Basic Authentication
094         * specification (RFC 2617).
095         *
096         * <p>Example HTTP Authorization header (for client identifier
097         * "Aladdin" and password "open sesame"):
098         *
099         * <pre>
100         *
101         * Authorization: Basic QWxhZGRpbjpvcGVuK3Nlc2FtZQ==
102         * </pre>
103         *
104         * <p>See RFC 2617, section 2.
105         *
106         * @return The HTTP Authorization header.
107         */
108        public String toHTTPAuthorizationHeader() {
109
110                StringBuilder sb = new StringBuilder();
111
112                try {
113                        sb.append(URLEncoder.encode(getClientID().getValue(), UTF8_CHARSET.name()));
114                        sb.append(':');
115                        sb.append(URLEncoder.encode(getClientSecret().getValue(), UTF8_CHARSET.name()));
116
117                } catch (UnsupportedEncodingException e) {
118
119                        // UTF-8 should always be supported
120                }
121
122                return "Basic " + Base64.encode(sb.toString().getBytes(UTF8_CHARSET));
123        }
124        
125        
126        @Override
127        public void applyTo(final HTTPRequest httpRequest) {
128        
129                httpRequest.setAuthorization(toHTTPAuthorizationHeader());
130        }
131        
132        
133        /**
134         * Parses a client secret basic authentication from the specified HTTP
135         * Authorization header.
136         *
137         * @param header The HTTP Authorization header to parse. Must not be 
138         *               {@code null}.
139         *
140         * @return The client secret basic authentication.
141         *
142         * @throws ParseException If the header couldn't be parsed to a client
143         *                        secret basic authentication.
144         */
145        public static ClientSecretBasic parse(final String header)
146                throws ParseException {
147                
148                String[] parts = header.split("\\s");
149                
150                if (parts.length != 2)
151                        throw new ParseException("Malformed client secret basic authentication (see RFC 6749, section 2.3.1): Unexpected number of HTTP Authorization header value parts: " + parts.length);
152                
153                if (! parts[0].equalsIgnoreCase("Basic"))
154                        throw new ParseException("HTTP authentication must be Basic");
155                
156                String credentialsString = new String(new Base64(parts[1]).decode(), UTF8_CHARSET);
157
158                String[] credentials = credentialsString.split(":", 2);
159                
160                if (credentials.length != 2)
161                        throw new ParseException("Malformed client secret basic authentication (see RFC 6749, section 2.3.1): Missing credentials delimiter (:)");
162
163                try {
164                        String decodedClientID = URLDecoder.decode(credentials[0], UTF8_CHARSET.name());
165                        String decodedSecret = URLDecoder.decode(credentials[1], UTF8_CHARSET.name());
166                        
167                        return new ClientSecretBasic(new ClientID(decodedClientID), new Secret(decodedSecret));
168                        
169                } catch (IllegalArgumentException | UnsupportedEncodingException e) {
170                
171                        throw new ParseException("Malformed client secret basic authentication (see RFC 6749, section 2.3.1): Invalid URL encoding", e);
172                }
173        }
174        
175        
176        /**
177         * Parses a client secret basic authentication from the specified HTTP
178         * request.
179         *
180         * @param httpRequest The HTTP request to parse. Must not be 
181         *                    {@code null} and must contain a valid 
182         *                    Authorization header.
183         *
184         * @return The client secret basic authentication.
185         *
186         * @throws ParseException If the HTTP Authorization header couldn't be 
187         *                        parsed to a client secret basic 
188         *                        authentication.
189         */
190        public static ClientSecretBasic parse(final HTTPRequest httpRequest)
191                throws ParseException {
192                
193                String header = httpRequest.getAuthorization();
194                
195                if (header == null)
196                        throw new ParseException("Missing HTTP Authorization header");
197                        
198                return parse(header);
199        }
200}