TenantJwtIssuerValidator.java

/*
 * Copyright 2022 Global Crop Diversity Trust
 *
 * 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
 *
 *   http://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 org.gringlobal.oauth2.server;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtIssuerValidator;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class TenantJwtIssuerValidator implements OAuth2TokenValidator<Jwt> {

	private final TenantRepository tenants;

	private final Map<String, JwtIssuerValidator> validators = new ConcurrentHashMap<>();

	public TenantJwtIssuerValidator(TenantRepository tenants) {
		this.tenants = tenants;
	}

	@Override
	public OAuth2TokenValidatorResult validate(Jwt token) {
		log.trace("Validating {}", token);
		return this.validators.computeIfAbsent(toTenant(token), this::fromTenant).validate(token);
	}

	private String toTenant(Jwt jwt) {
		log.trace("Getting issuer from {}", jwt);
		return jwt.getIssuer().toString();
	}

	private JwtIssuerValidator fromTenant(String tenant) {
		log.trace("Getting tenant for {}", tenant);
		return Optional.ofNullable(this.tenants.findByIssuer(tenant))
			.map(cr -> cr.getProviderDetails().getIssuerUri())
			.map(JwtIssuerValidator::new)
			.orElseThrow(() -> new IllegalArgumentException("unknown tenant"));
	}
}