All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.micronaut.security.token.jwt.nimbus.NimbusJsonWebTokenSignatureValidator Maven / Gradle / Ivy

/*
 * Copyright 2017-2024 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micronaut.security.token.jwt.nimbus;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jwt.SignedJWT;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.security.token.jwt.signature.SignatureConfiguration;
import io.micronaut.security.token.jwt.validator.JsonWebTokenSignatureValidator;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Validates the signature of a JSON Web Token using Nimbus JOSE + JWT.
 * @author Sergio del Amo
 * @since 4.8.0
 */
@Internal
@Singleton
class NimbusJsonWebTokenSignatureValidator implements JsonWebTokenSignatureValidator {
    private static final Logger LOG = LoggerFactory.getLogger(NimbusJsonWebTokenSignatureValidator.class);
    private final List signatures;
    private final ConcurrentHashMap> sortedSignaturesMap = new ConcurrentHashMap<>();

    public NimbusJsonWebTokenSignatureValidator(List signatures) {
        this.signatures = signatures;
    }

    @Override
    public boolean validateSignature(@NonNull SignedJWT signedToken) {
        List sortedSignatures = sortedSignaturesMap.computeIfAbsent(signedToken.getHeader().getAlgorithm(), alg -> {
            List sortedConfigs = new ArrayList<>(signatures);
            sortedConfigs.sort(comparator(alg));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Sorted signature configurations for algorithm {} : {}", alg, sortedConfigs);
            }
            return sortedConfigs;
        });
        return validate(signedToken, sortedSignatures);
    }

    private static boolean validate(SignedJWT jwt, SignatureConfiguration signatureConfiguration) {
        try {
            boolean verified = signatureConfiguration.verify(jwt);
            if (verified) {
                return true;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("JWT Signature verification failed: {}", jwt.getParsedString());
            }
        } catch (final JOSEException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Verification failed with signature configuration: {}, passing to the next one", signatureConfiguration);
            }
        }
        return false;
    }

    private static boolean validate(SignedJWT jwt, List signatureConfigurations) {
        for (SignatureConfiguration config: signatureConfigurations) {
            if (validate(jwt, config)) {
                return true;
            }
        }
        return false;
    }

    private static Comparator comparator(JWSAlgorithm algorithm) {
        return (sig, otherSig) -> {
            boolean supports = sig.supports(algorithm);
            boolean otherSupports = otherSig.supports(algorithm);
            if (supports == otherSupports) {
                return 0;
            } else if (supports) {
                return -1;
            } else {
                return 1;
            }
        };
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy