de.tbosch.tools.googleapps.oauth2.OAuth2SaslClientFactory.java Source code

Java tutorial

Introduction

Here is the source code for de.tbosch.tools.googleapps.oauth2.OAuth2SaslClientFactory.java

Source

/* Copyright 2012 Google Inc.
 *
 * 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 de.tbosch.tools.googleapps.oauth2;

import java.util.Map;

import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslClientFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A SaslClientFactory that returns instances of OAuth2SaslClient.
 * 
 * <p>
 * Only the "XOAUTH2" mechanism is supported. The {@code callbackHandler} is passed to the OAuth2SaslClient. Other
 * parameters are ignored.
 */
public class OAuth2SaslClientFactory implements SaslClientFactory {

    private static final Log LOG = LogFactory.getLog(OAuth2SaslClientFactory.class);

    public static final String OAUTH_TOKEN_PROP = "mail.imaps.sasl.mechanisms.oauth2.oauthToken";

    @Override
    public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol,
            String serverName, Map<String, ?> props, CallbackHandler callbackHandler) {
        boolean matchedMechanism = false;
        for (int i = 0; i < mechanisms.length; ++i) {
            if ("XOAUTH2".equalsIgnoreCase(mechanisms[i])) {
                matchedMechanism = true;
                break;
            }
        }
        if (!matchedMechanism) {
            LOG.info("Failed to match any mechanisms");
            return null;
        }
        return new OAuth2SaslClient((String) props.get(OAUTH_TOKEN_PROP), callbackHandler);
    }

    @Override
    public String[] getMechanismNames(Map<String, ?> props) {
        return new String[] { "XOAUTH2" };
    }
}