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.openid.connect.sdk.validators;
019
020
021import com.nimbusds.jose.JWSAlgorithm;
022import com.nimbusds.oauth2.sdk.AuthorizationCode;
023import com.nimbusds.openid.connect.sdk.claims.CodeHash;
024import net.jcip.annotations.ThreadSafe;
025
026
027/**
028 * Authorisation code validator, using the {@code c_hash} ID token claim.
029 * Required in the hybrid flow where the authorisation code is returned
030 * together with an ID token at the authorisation endpoint.
031 *
032 * <p>Related specifications:
033 *
034 * <ul>
035 *     <li>OpenID Connect Core 1.0, section 3.3.2.10.
036 * </ul>
037 */
038@ThreadSafe
039public class AuthorizationCodeValidator {
040        
041
042        /**
043         * Validates the specified authorisation code.
044         *
045         * @param code         The authorisation code. Must not be
046         *                     {@code null}.
047         * @param jwsAlgorithm The JWS algorithm of the ID token. Must not
048         *                     be {@code null}.=
049         * @param codeHash     The authorisation code hash, as set in the
050         *                     {@code c_hash} ID token claim. Must not be
051         *                     {@code null}.
052         *
053         * @throws InvalidHashException If the authorisation code doesn't match
054         *                              the hash.
055         */
056        public static void validate(final AuthorizationCode code,
057                                    final JWSAlgorithm jwsAlgorithm,
058                                    final CodeHash codeHash)
059                throws InvalidHashException {
060
061                CodeHash expectedHash = CodeHash.compute(code, jwsAlgorithm);
062
063                if (expectedHash == null) {
064                        throw InvalidHashException.INVALID_CODE_HASH_EXCEPTION;
065                }
066
067                if (! expectedHash.equals(codeHash)) {
068                        throw InvalidHashException.INVALID_CODE_HASH_EXCEPTION;
069                }
070        }
071}