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;
026
027import net.jcip.annotations.Immutable;
028
029import com.nimbusds.jose.util.Base64;
030
031import com.nimbusds.oauth2.sdk.ParseException;
032import com.nimbusds.oauth2.sdk.id.ClientID;
033import com.nimbusds.oauth2.sdk.http.HTTPRequest;
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), sections 2.3.1 and 3.2.1.
051 *     <li>OpenID Connect Core 1.0, section 9.
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        /**
079         * Returns the HTTP Authorization header representation of this client
080         * secret basic authentication.
081         *
082         * <p>Note that OAuth 2.0 (RFC 6749, section 2.3.1) requires the client
083         * ID and secret to be {@code application/x-www-form-urlencoded} before
084         * passing them to the HTTP basic authentication algorithm. This
085         * behaviour differs from the original HTTP Basic Authentication
086         * specification (RFC 2617).
087         *
088         * <p>Example HTTP Authorization header (for client identifier
089         * "Aladdin" and password "open sesame"):
090         *
091         * <pre>
092         *
093         * Authorization: Basic QWxhZGRpbjpvcGVuK3Nlc2FtZQ==
094         * </pre>
095         *
096         * <p>See RFC 2617, section 2.
097         *
098         * @return The HTTP Authorization header.
099         */
100        public String toHTTPAuthorizationHeader() {
101
102                StringBuilder sb = new StringBuilder();
103
104                try {
105                        sb.append(URLEncoder.encode(getClientID().getValue(), UTF8_CHARSET.name()));
106                        sb.append(':');
107                        sb.append(URLEncoder.encode(getClientSecret().getValue(), UTF8_CHARSET.name()));
108
109                } catch (UnsupportedEncodingException e) {
110
111                        // UTF-8 should always be supported
112                }
113
114                return "Basic " + Base64.encode(sb.toString().getBytes(UTF8_CHARSET));
115        }
116        
117        
118        @Override
119        public void applyTo(final HTTPRequest httpRequest) {
120        
121                httpRequest.setAuthorization(toHTTPAuthorizationHeader());
122        }
123        
124        
125        /**
126         * Parses a client secret basic authentication from the specified HTTP
127         * Authorization header.
128         *
129         * @param header The HTTP Authorization header to parse. Must not be 
130         *               {@code null}.
131         *
132         * @return The client secret basic authentication.
133         *
134         * @throws ParseException If the header couldn't be parsed to a client
135         *                        secret basic authentication.
136         */
137        public static ClientSecretBasic parse(final String header)
138                throws ParseException {
139                
140                String[] parts = header.split("\\s");
141                
142                if (parts.length != 2)
143                        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);
144                
145                if (! parts[0].equalsIgnoreCase("Basic"))
146                        throw new ParseException("HTTP authentication must be \"Basic\"");
147                
148                String credentialsString = new String(new Base64(parts[1]).decode(), UTF8_CHARSET);
149
150                String[] credentials = credentialsString.split(":", 2);
151                
152                if (credentials.length != 2)
153                        throw new ParseException("Malformed client secret basic authentication (see RFC 6749, section 2.3.1): Missing credentials delimiter \":\"");
154
155                try {
156                        String decodedClientID = URLDecoder.decode(credentials[0], UTF8_CHARSET.name());
157                        String decodedSecret = URLDecoder.decode(credentials[1], UTF8_CHARSET.name());
158                        
159                        return new ClientSecretBasic(new ClientID(decodedClientID), new Secret(decodedSecret));
160                        
161                } catch (IllegalArgumentException | UnsupportedEncodingException e) {
162                
163                        throw new ParseException("Malformed client secret basic authentication (see RFC 6749, section 2.3.1): Invalid URL encoding", e);
164                }
165        }
166        
167        
168        /**
169         * Parses a client secret basic authentication from the specified HTTP
170         * request.
171         *
172         * @param httpRequest The HTTP request to parse. Must not be 
173         *                    {@code null} and must contain a valid 
174         *                    Authorization header.
175         *
176         * @return The client secret basic authentication.
177         *
178         * @throws ParseException If the HTTP Authorization header couldn't be 
179         *                        parsed to a client secret basic 
180         *                        authentication.
181         */
182        public static ClientSecretBasic parse(final HTTPRequest httpRequest)
183                throws ParseException {
184                
185                String header = httpRequest.getAuthorization();
186                
187                if (header == null)
188                        throw new ParseException("Missing HTTP Authorization header");
189                        
190                return parse(header);
191        }
192}