001/*
002 * oauth2-oidc-sdk
003 *
004 * Copyright 2012-2021, 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.ciba;
019
020
021import java.net.URI;
022import java.net.URISyntaxException;
023
024import net.jcip.annotations.Immutable;
025import net.minidev.json.JSONObject;
026
027import com.nimbusds.common.contenttype.ContentType;
028import com.nimbusds.oauth2.sdk.ParseException;
029import com.nimbusds.oauth2.sdk.http.HTTPRequest;
030import com.nimbusds.oauth2.sdk.token.BearerAccessToken;
031import com.nimbusds.oauth2.sdk.token.Tokens;
032import com.nimbusds.oauth2.sdk.util.JSONObjectUtils;
033import com.nimbusds.openid.connect.sdk.token.OIDCTokens;
034
035
036/**
037 * CIBA token push delivery to the client notification endpoint.
038 *
039 * <p>Example HTTP request:
040 *
041 * <pre>
042 * POST /cb HTTP/1.1
043 * Host: client.example.com
044 * Authorization: Bearer 8d67dc78-7faa-4d41-aabd-67707b374255
045 * Content-Type: application/json
046 *
047 * {
048 *   "auth_req_id": "1c266114-a1be-4252-8ad1-04986c5b9ac1",
049 *   "access_token": "G5kXH2wHvUra0sHlDy1iTkDJgsgUO1bN",
050 *   "token_type": "Bearer",
051 *   "refresh_token": "4bwc0ESC_IAhflf-ACC_vjD_ltc11ne-8gFPfA2Kx16",
052 *   "expires_in": 120,
053 *   "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjE2NzcyNiJ9.eyJpc3MiOiJ
054 *     odHRwczovL3NlcnZlci5leGFtcGxlLmNvbSIsInN1YiI6IjI0ODI4OTc2MTAwMS
055 *     IsImF1ZCI6InM2QmhkUmtxdDMiLCJlbWFpbCI6ImphbmVkb2VAZXhhbXBsZS5jb
056 *     20iLCJleHAiOjE1Mzc4MTk4MDMsImlhdCI6MTUzNzgxOTUwMywiYXRfaGFzaCI6
057 *     Ild0MGtWRlhNYWNxdm5IZXlVMDAwMXciLCJ1cm46b3BlbmlkOnBhcmFtczpqd3Q
058 *     6Y2xhaW06cnRfaGFzaCI6InNIYWhDdVNwWENSZzVta0REdnZyNHciLCJ1cm46b3
059 *     BlbmlkOnBhcmFtczpqd3Q6Y2xhaW06YXV0aF9yZXFfaWQiOiIxYzI2NjExNC1hM
060 *     WJlLTQyNTItOGFkMS0wNDk4NmM1YjlhYzEifQ.SGB5_a8E7GjwtoYrkFyqOhLK6
061 *     L8-Wh1nLeREwWj30gNYOZW_ZB2mOeQ5yiXqeKJeNpDPssGUrNo-3N-CqNrbmVCb
062 *     XYTwmNB7IvwE6ZPRcfxFV22oou-NS4-3rEa2ghG44Fi9D9fVURwxrRqgyezeD3H
063 *     HVIFUnCxHUou3OOpj6aOgDqKI4Xl2xJ0-kKAxNR8LljUp64OHgoS-UO3qyfOwIk
064 *     IAR7o4OTK_3Oy78rJNT0Y0RebAWyA81UDCSf_gWVBp-EUTI5CdZ1_odYhwB9OWD
065 *     W1A22Sf6rmjhMHGbQW4A9Z822yiZZveuT_AFZ2hi7yNp8iFPZ8fgPQJ5pPpjA7u
066 *     dg"
067 * }
068 * </pre>
069 *
070 * <p>Related specifications:
071 *
072 * <ul>
073 *      <li>OpenID Connect CIBA Flow - Core 1.0, section 10.3.1.
074 * </ul>
075 */
076@Immutable
077public class CIBATokenDelivery extends CIBAPushCallback {
078        
079        
080        /**
081         * The tokens.
082         */
083        private final Tokens tokens;
084        
085        
086        /**
087         * Creates a new CIBA push token delivery for OAuth 2.0.
088         *
089         * @param endpoint      The client notification endpoint. Must not be
090         *                      {@code null}.
091         * @param accessToken   The client notification token. Must not be
092         *                      {@code null}.
093         * @param authRequestID The CIBA request ID. Must not be {@code null}.
094         * @param tokens        The OAuth 2.0 tokens to deliver. Must not be
095         *                      {@code null}.
096         */
097        public CIBATokenDelivery(final URI endpoint,
098                                 final BearerAccessToken accessToken,
099                                 final AuthRequestID authRequestID,
100                                 final Tokens tokens) {
101                
102                super(endpoint, accessToken, authRequestID);
103                
104                if (tokens == null) {
105                        throw new IllegalArgumentException("The tokens must not be null");
106                }
107                this.tokens = tokens;
108        }
109        
110        
111        /**
112         * Creates a new CIBA push token delivery for OpenID Connect.
113         *
114         * @param endpoint      The client notification endpoint. Must not be
115         *                      {@code null}.
116         * @param accessToken   The client notification token. Must not be
117         *                      {@code null}.
118         * @param authRequestID The CIBA request ID. Must not be {@code null}.
119         * @param oidcTokens    The OpenID Connect tokens to deliver. Must not
120         *                      be {@code null}.
121         */
122        public CIBATokenDelivery(final URI endpoint,
123                                 final BearerAccessToken accessToken,
124                                 final AuthRequestID authRequestID,
125                                 final OIDCTokens oidcTokens) {
126                
127                super(endpoint, accessToken, authRequestID);
128                
129                if (oidcTokens == null) {
130                        throw new IllegalArgumentException("The OpenID Connect tokens must not be null");
131                }
132                this.tokens = oidcTokens;
133        }
134        
135        
136        @Override
137        public boolean indicatesSuccess() {
138                
139                return true;
140        }
141        
142        
143        /**
144         * Returns the OAuth 2.0 tokens.
145         *
146         * @return The tokens.
147         */
148        public Tokens getTokens() {
149                
150                return tokens;
151        }
152        
153        
154        /**
155         * Returns the OpenID Connect tokens if present.
156         *
157         * @return The OpenID Connect tokens, {@code null} if none.
158         */
159        public OIDCTokens getOIDCTokens() {
160                
161                return getTokens() instanceof OIDCTokens ? getTokens().toOIDCTokens() : null;
162        }
163        
164        
165        @Override
166        public HTTPRequest toHTTPRequest() {
167                
168                HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, getEndpointURI());
169                httpRequest.setAuthorization(getAccessToken().toAuthorizationHeader());
170                httpRequest.setEntityContentType(ContentType.APPLICATION_JSON);
171                JSONObject jsonObject = new JSONObject();
172                jsonObject.put("auth_req_id", getAuthRequestID().getValue());
173                jsonObject.putAll(getTokens().toJSONObject());
174                httpRequest.setQuery(jsonObject.toJSONString());
175                return httpRequest;
176        }
177        
178        
179        /**
180         * Parses a CIBA push token delivery from the specified HTTP request.
181         *
182         * @param httpRequest The HTTP request. Must not be {@code null}.
183         *
184         * @return The CIBA push token delivery.
185         *
186         * @throws ParseException If parsing failed.
187         */
188        public static CIBATokenDelivery parse(final HTTPRequest httpRequest)
189                throws ParseException {
190                
191                URI uri = httpRequest.getURI();
192                httpRequest.ensureMethod(HTTPRequest.Method.POST);
193                httpRequest.ensureEntityContentType(ContentType.APPLICATION_JSON);
194                
195                BearerAccessToken clientNotificationToken = BearerAccessToken.parse(httpRequest);
196                
197                AuthRequestID authRequestID = new AuthRequestID(
198                        JSONObjectUtils.getString(
199                                httpRequest.getQueryAsJSONObject(),
200                                "auth_req_id"));
201                
202                JSONObject jsonObject = httpRequest.getQueryAsJSONObject();
203                
204                if (jsonObject.get("id_token") != null) {
205                        return new CIBATokenDelivery(
206                                uri,
207                                clientNotificationToken,
208                                authRequestID,
209                                OIDCTokens.parse(jsonObject));
210                } else {
211                        return new CIBATokenDelivery(
212                                uri,
213                                clientNotificationToken,
214                                authRequestID,
215                                Tokens.parse(jsonObject));
216                }
217        }
218}