001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.revetsec.servlet.javax; 017 018import com.google.errorprone.annotations.CheckReturnValue; 019import com.revetsec.oauth.BearerToken; 020import com.revetsec.oauth.BearerTokenResult; 021import javax.servlet.http.HttpServletRequest; 022import org.jspecify.annotations.NonNull; 023 024import javax.annotation.concurrent.ThreadSafe; 025import java.util.ArrayList; 026import java.util.Enumeration; 027import java.util.List; 028 029import static java.util.Objects.requireNonNull; 030 031/** Raw Authorization-header transport. A parsed bearer credential remains unverified. 032 * @since 1.0.0 033 */ 034@ThreadSafe 035public final class ServletBearer { 036 private ServletBearer() { } 037 038 /** Parses every materialized Authorization occurrence without joining or trimming fields. 039 * @param request application-routed resource request 040 * @return absent, unverified present or malformed result 041 * @since 1.0.0 042 */ 043 @CheckReturnValue 044 public static @NonNull BearerTokenResult bearerTokenResultFor(@NonNull HttpServletRequest request) { 045 return BearerToken.fromAuthorizationHeaderValuesResult(authorizationValues(requireNonNull(request))); 046 } 047 048 private static @NonNull List<@NonNull String> authorizationValues(@NonNull HttpServletRequest request) { 049 List<String> values = new ArrayList<>(2); 050 Enumeration<String> original = request.getHeaders("Authorization"); 051 if (original == null) throw new IllegalStateException("Servlet request headers are unavailable"); 052 while (original.hasMoreElements() && values.size() < 2) 053 values.add(requireNonNull(original.nextElement())); 054 return List.copyOf(values); 055 } 056}