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.genesys.spring.security;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import java.net.URL;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class TenantJwtIssuerValidator implements OAuth2TokenValidator<Jwt> {
private Logger LOG = LoggerFactory.getLogger(TenantJwtIssuerValidator.class);
private final TenantRepository tenants;
private final Map<URL, 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 URL toTenant(Jwt jwt) {
LOG.trace("Getting issuer from {}", jwt);
return jwt.getIssuer();
}
private JwtIssuerValidator fromTenant(URL tenant) {
LOG.trace("Getting tenant for {}", tenant);
return Optional.ofNullable(this.tenants.findByIssuer(tenant.toString()))
.map(cr -> cr.getProviderDetails().getIssuerUri())
.map(JwtIssuerValidator::new)
.orElseThrow(() -> new IllegalArgumentException("unknown tenant"));
}
}