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