InvalidatedTokenFilter.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.blocks.security.filter;

import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.oauth.service.OAuthClientService;
import org.genesys.blocks.tokenauth.service.ApiTokenService;
import org.genesys.blocks.tokenauth.spring.ApiTokenAuthenticationFilter;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.filter.OncePerRequestFilter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class InvalidatedTokenFilter extends OncePerRequestFilter {

	private final OAuth2AuthorizationService authorizationService;

	private final ApiTokenService apiTokenService;

	private final OAuthClientService oAuthClientService;

	public InvalidatedTokenFilter(OAuth2AuthorizationService authorizationService, ApiTokenService apiTokenService, OAuthClientService oAuthClientService) {
		this.authorizationService = authorizationService;
		this.apiTokenService = apiTokenService;
		this.oAuthClientService = oAuthClientService;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String authorizationHeader = request.getHeader("Authorization");

		if (StringUtils.isNotBlank(authorizationHeader)) {
			if (authorizationHeader.startsWith("Bearer ")) {
				String accessToken = authorizationHeader.substring(7);

				OAuth2Authorization authorization = this.authorizationService.findByToken(accessToken, OAuth2TokenType.ACCESS_TOKEN);
				if (authorization != null) {
					OAuth2Authorization.Token<OAuth2AccessToken> authorizedToken = authorization.getAccessToken();
					if (authorizedToken != null && !authorizedToken.isActive()) {
						log.debug("Access token is invalidated for authorization id = {}", authorization.getId());
						throw new AuthenticationCredentialsNotFoundException("Access token is invalidated");
					}
					if (!oAuthClientService.isClientActive(authorization.getRegisteredClientId())) {
						log.debug("Client {} is not active", authorization.getRegisteredClientId());
						throw new AuthenticationCredentialsNotFoundException("Client is not active");
					}
				} else {
					throw new AuthenticationCredentialsNotFoundException("Access token is invalidated");
				}
			} else if (StringUtils.startsWithIgnoreCase(authorizationHeader, ApiTokenAuthenticationFilter.AUTHORIZATION_TYPE)) {
				String token = authorizationHeader.substring(10);
				if (apiTokenService == null) {
					log.warn("Cannot check API-Token validity without ApiTokenService");
					throw new AuthenticationCredentialsNotFoundException("API-Token authentication not supported");
				} else {
					var apiToken = apiTokenService.getToken(apiTokenService.encodeToken(token));
					if (apiToken == null) {
						throw new AuthenticationCredentialsNotFoundException("Invalid API token");
					}
					if (!apiToken.isCredentialsNonExpired()) {
						throw new AuthenticationCredentialsNotFoundException("API token expired");
					}
				}
			}
		}
		filterChain.doFilter(request, response);
	}
}