fi.vm.kapa.identification.shibboleth.extattribute.ShibbolethExtAttributeConnector.java Source code

Java tutorial

Introduction

Here is the source code for fi.vm.kapa.identification.shibboleth.extattribute.ShibbolethExtAttributeConnector.java

Source

/**
 * The MIT License
 * Copyright (c) 2015 Population Register Centre
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package fi.vm.kapa.identification.shibboleth.extattribute;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.shibboleth.idp.attribute.IdPAttribute;
import net.shibboleth.idp.attribute.IdPAttributeValue;
import net.shibboleth.idp.attribute.StringAttributeValue;
import net.shibboleth.idp.attribute.resolver.AbstractDataConnector;
import net.shibboleth.idp.attribute.resolver.ResolutionException;
import net.shibboleth.idp.attribute.resolver.context.AttributeResolutionContext;
import net.shibboleth.idp.attribute.resolver.context.AttributeResolverWorkContext;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ShibbolethExtAttributeConnector extends AbstractDataConnector {

    private final Logger logger = LoggerFactory.getLogger(ShibbolethExtAttributeConnector.class);
    private final static int HTTP_OK = 200;

    private String adapterUrl;

    @Nullable
    @Override
    protected Map<String, IdPAttribute> doDataConnectorResolve(
            @Nonnull AttributeResolutionContext attributeResolutionContext,
            @Nonnull AttributeResolverWorkContext attributeResolverWorkContext) throws ResolutionException {
        Map<String, IdPAttribute> attributes = new HashMap<>();

        logger.debug("Trying to resolve attributes from adapter REST URL: " + adapterUrl);

        String token = attributeResolutionContext.getPrincipal();

        logger.debug("Using token: '{}' to fetch session attributes", token);

        try {
            String attributeCallUrl = adapterUrl + "?token=" + token;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet getMethod = new HttpGet(attributeCallUrl);
            HttpContext context = HttpClientContext.create();

            CloseableHttpResponse restResponse = httpClient.execute(getMethod, context);

            int status = restResponse.getStatusLine().getStatusCode();

            logger.debug("Response code from adapter HTTP " + status);

            if (status == HTTP_OK) {
                Gson gson = new Gson();

                Map<String, String> attributeMap = gson.fromJson(EntityUtils.toString(restResponse.getEntity()),
                        new TypeToken<Map<String, String>>() {
                        }.getType());

                if (attributeMap != null) {
                    logger.debug("Attribute map size: {}", attributeMap.size());

                    attributeMap.keySet().forEach(key -> {
                        String value = attributeMap.get(key);

                        logger.debug("--attribute key: {}, attribute value: {}", key, value);

                        if (StringUtils.isNotBlank(value)) {
                            IdPAttribute idPAttribute = new IdPAttribute(key);
                            List<IdPAttributeValue<String>> values = new ArrayList<>();
                            values.add(new StringAttributeValue(value));
                            idPAttribute.setValues(values);
                            attributes.put(key, idPAttribute);
                        }
                    });
                } else {
                    logger.warn("Attribute fetch OK but no content was found");
                }
            } else {
                logger.warn("No attributes found for session");
            }
        } catch (Exception e) {
            logger.error("Error in connection to Adapter", e);
        }

        return attributes;
    }

    public void setAdapterUrl(String adapterUrl) {
        this.adapterUrl = adapterUrl;
    }
}