001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2014 ForgeRock AS.
015 */
016
017package org.forgerock.openig.filter.oauth2;
018
019/**
020 * Extracts the bearer token from the request's authorization header.
021 * <p>
022 * Expected ABNF format (as per RFC 6750):
023 * <pre>
024 *     b64token    = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
025 *     credentials = "Bearer" 1*SP b64token
026 * </pre>
027 */
028public class BearerTokenExtractor {
029
030    private static final String BEARER_TOKEN_KEY = "BEARER";
031
032    /**
033     * Pulls the access token off of the request, by looking for the Authorization header containing a Bearer token.
034     *
035     * @param authorizationHeader The authorization header from the request.
036     * @return The access token, or <code>null</code> if the access token was not present or was not using Bearer
037     * authorization.
038     */
039    public String getAccessToken(final String authorizationHeader) {
040
041        if (authorizationHeader == null) {
042            return null;
043        }
044        String authorization = authorizationHeader.trim();
045        final int index = authorization.indexOf(' ');
046        if (index <= 0) {
047            return null;
048        }
049
050        final String tokenType = authorization.substring(0, index);
051
052        if (BEARER_TOKEN_KEY.equalsIgnoreCase(tokenType)) {
053            return authorization.substring(index + 1);
054        }
055
056        return null;
057    }
058}