AccessTokenAsParameterFilter.java

/*
 * Copyright 2023 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.spring;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;;

/**
 * Converts the API cookie to the "Authorization" HTTP request
 * header if provided.
 * Will Set-Cookie when cookie is missing.
 *
 * @author Maxym Borodenko
 * @author Matija Obreza
 */
@Slf4j
public class AccessTokenAsParameterFilter extends OncePerRequestFilter {

	private static final String ACCESS_TOKEN_PARAM_NAME = "_access_token";

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

		String authorizationHeader = request.getHeader("Authorization");
		String accessToken = null;

		// 1. Check if _access_token is present
		if (authorizationHeader == null) {
//			if (request.getQueryString().contains(ACCESS_TOKEN_PARAM_NAME.concat("="))) {
//				throw new InvalidApiUsageException(ACCESS_TOKEN_PARAM_NAME + " can only be used as a form parameter");
//			}
			accessToken = request.getParameter(ACCESS_TOKEN_PARAM_NAME);
		}

		// 2. Apply form token -- using CustomHeadersRequest
		if (authorizationHeader == null && StringUtils.isNotBlank(accessToken)) {
			log.debug("Using access token from cookie!");
			request = new CustomHeadersRequest(request);
			((CustomHeadersRequest) request).addHeader("Authorization", "Bearer " + accessToken);
		}

		filterChain.doFilter(request, response);
	}

	static class CustomHeadersRequest extends HttpServletRequestWrapper {
		private final Map<String, String> customHeaders = new HashMap<>();

		public CustomHeadersRequest(HttpServletRequest request) {
			super(request);
		}

		public void addHeader(String name, String value) {
			customHeaders.put(name, value);
		}

		@Override
		public String getHeader(String name) {
			var customHeader = customHeaders.get(name);
			return customHeader != null ? customHeader : super.getHeader(name);
		}

		@Override
		public Enumeration<String> getHeaderNames() {
			List<String> names = Collections.list(super.getHeaderNames());
			names.addAll(customHeaders.keySet());
			return Collections.enumeration(names);
		}

		@Override
		public Enumeration<String> getHeaders(String name) {
			List<String> values = Collections.list(super.getHeaders(name));
			var customHeader = customHeaders.get(name);
			if (customHeader != null) values.add(customHeader);
			
			return Collections.enumeration(values);
		}
	}
}