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