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.id.State;
023import com.nimbusds.openid.connect.sdk.claims.StateHash;
024import net.jcip.annotations.ThreadSafe;
025
026
027/**
028 * State validator, using the optional {@code s_hash} ID token claim. Required
029 * for applications that must comply with Financial Services – Financial API -
030 * Part 2: Read and Write API Security Profile.
031 *
032 * <p>Related specifications:
033 *
034 * <ul>
035 *     <li>Financial Services – Financial API - Part 2: Read and Write API
036 *         Security Profile, section 5.1.
037 * </ul>
038 */
039@ThreadSafe
040public class StateValidator {
041        
042        
043        /**
044         * Validates the specified state.
045         *
046         * @param state        The state received at the redirection URI. Must
047         *                     not be {@code null}.
048         * @param jwsAlgorithm The JWS algorithm of the ID token. Must not be
049         *                     be {@code null}.
050         * @param stateHash    The state hash, as set in the {@code s_hash} ID
051         *                     token claim. Must not be {@code null}.
052         *
053         * @throws InvalidHashException If the received state doesn't match the
054         *                              hash.
055         */
056        public static void validate(final State state,
057                                    final JWSAlgorithm jwsAlgorithm,
058                                    final StateHash stateHash)
059                throws InvalidHashException {
060                
061                StateHash expectedHash = StateHash.compute(state, jwsAlgorithm);
062                
063                if (expectedHash == null) {
064                        throw InvalidHashException.INVALID_STATE_HASH_EXCEPTION;
065                }
066                
067                if (! expectedHash.equals(stateHash)) {
068                        throw InvalidHashException.INVALID_STATE_HASH_EXCEPTION;
069                }
070        }
071}