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