All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.xlcloud.rest.AuthorizationTokenResolver Maven / Gradle / Ivy

/*
 * Copyright 2012 AMG.lab, a Bull Group Company
 * 
 * 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.xlcloud.rest;

import org.apache.commons.lang.StringUtils;

import org.xlcloud.rest.exception.AuthenticateException;
import org.xlcloud.rest.exception.ValidationException;
import com.sun.jersey.spi.container.ContainerRequest;

/**
 * Resolves the OAuth token value from HTTP header value.
 * 
 * @author Piotr Kulasek-Szwed, AMG.net
 */
public class AuthorizationTokenResolver {

    public static final String BEARER_TOKEN_PREFIX = "Bearer ";

    public static final String AUTH_HEADER_NAME = "Authorization";

    /**
     * @param request
     * @return return access token without prefix (
     *         {@link AuthorizationTokenResolver.BEARER_TOKEN_PREFIX}) or empty
     *         string if request does not contain
     *         {@link AuthorizationTokenResolver.AUTH_HEADER_NAME} header.
     */
    public String get(RequestAwareResource target) {
        String dirtyToken = RequestUtils.optHeaderValue(target, AUTH_HEADER_NAME);
        
        if(dirtyToken == null){
            throw new AuthenticateException("Authorization header is missing", AuthenticateException.AuthenticationFailureType.MISSING_AUTH_HEADER);
        }

        return parse(dirtyToken);
    }

    /**
     * @param request
     * @return return access token without prefix (
     *         {@link AuthorizationTokenResolver.BEARER_TOKEN_PREFIX}) or empty
     *         string if request does not contain
     *         {@link AuthorizationTokenResolver.AUTH_HEADER_NAME} header.
     */
    public String get(ContainerRequest request) {
        String dirtyToken = request.getHeaderValue(AUTH_HEADER_NAME);
        return parse(dirtyToken);
    }

    private String parse(String dirtyToken) {
        if (StringUtils.isBlank(dirtyToken)) {
            return "";
        }

        if (!StringUtils.startsWith(dirtyToken, BEARER_TOKEN_PREFIX)) {
            throw new ValidationException("Authorization header must start with '" + BEARER_TOKEN_PREFIX +"'",
                    ValidationException.ValidationFailureType.AUTH_HEADER_FORMAT);
        }

        return StringUtils.substringAfter(dirtyToken, BEARER_TOKEN_PREFIX);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy