fi.csc.mobileauth.shibboleth.rest.MobileServiceLoginHandler.java Source code

Java tutorial

Introduction

Here is the source code for fi.csc.mobileauth.shibboleth.rest.MobileServiceLoginHandler.java

Source

/*
 * Copyright (c) 2014-2015 CSC - IT Center for Science, http://www.csc.fi
 *
 * CSC licenses this file to You 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 fi.csc.mobileauth.shibboleth.rest;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.util.URIUtil;
import org.opensaml.util.URLBuilder;
import org.opensaml.ws.soap.client.http.HttpClientBuilder;
import org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory;
import org.opensaml.xml.util.DatatypeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

import edu.internet2.middleware.shibboleth.idp.authn.UsernamePrincipal;
import edu.internet2.middleware.shibboleth.idp.authn.provider.AbstractLoginHandler;
import edu.internet2.middleware.shibboleth.idp.util.HttpServletHelper;
import eu.emi.security.authn.x509.helpers.ssl.CredentialX509KeyManager;
import eu.emi.security.authn.x509.helpers.ssl.SSLTrustManager;
import eu.emi.security.authn.x509.impl.KeystoreCertChainValidator;
import eu.emi.security.authn.x509.impl.KeystoreCredential;
import fi.csc.mobileauth.comm.CommunicationDataStore;
import fi.csc.mobileauth.etsi.FiComConstants;
import fi.csc.mobileauth.ldap.UserIdentifierResolver;
import fi.csc.mobileauth.principal.FiComAgePrincipal;
import fi.csc.mobileauth.principal.FiComGivenNamePrincipal;
import fi.csc.mobileauth.principal.FiComHetuPrincipal;
import fi.csc.mobileauth.principal.FiComSatuPrincipal;
import fi.csc.mobileauth.principal.FiComSurNamePrincipal;
import fi.csc.mobileauth.principal.MobileNumberPrincipal;
import fi.csc.mobileauth.rest.StatusResponse;
import fi.csc.mobileauth.shibboleth.rest.comm.TimestampedStatusResponse;

public class MobileServiceLoginHandler extends AbstractLoginHandler {

    /** Class logger. */
    private static final Logger log = LoggerFactory.getLogger(MobileServiceLoginHandler.class);

    private static String baseUrl;

    private static UserIdentifierResolver userIdentifierResolver;

    private static HttpClientBuilder httpClientBuilder;

    private static CommunicationDataStore<TimestampedStatusResponse> communicationDataStore;

    public MobileServiceLoginHandler() {
        super();
        setSupportsPassive(false);
        setSupportsForceAuthentication(true);
        log.debug("Mobile login handler has been initialized.");
    }

    public static void initializeHttpClientBuilder(String keystorePath, char[] keystorePasswd, char[] keyPasswd,
            String keyAlias, String keystoreType, String trustStorePath, String trustStoreType,
            char[] trustStorePassword) throws Exception {
        log.debug("Initializing a {} keystore from the file {}", keystoreType, keystorePath);
        KeystoreCredential credential = new KeystoreCredential(keystorePath, keystorePasswd, keyPasswd, keyAlias,
                keystoreType);
        log.debug("Keystore successfully initialized");
        KeystoreCertChainValidator validator = new KeystoreCertChainValidator(trustStorePath, trustStorePassword,
                trustStoreType, 60000);
        TLSProtocolSocketFactory socketFactory = new TLSProtocolSocketFactory(
                new CredentialX509KeyManager(credential), new SSLTrustManager(validator));
        httpClientBuilder = new HttpClientBuilder();
        httpClientBuilder.setHttpsProtocolSocketFactory(socketFactory);
        log.info("HttpClientBuilder successfully initialized");
    }

    public static String getBaseUrl() {
        return baseUrl;
    }

    public static void setBaseUrl(String url) {
        baseUrl = url;
    }

    public static void setUserIdentifierResolver(UserIdentifierResolver resolver) {
        userIdentifierResolver = resolver;
    }

    public static UserIdentifierResolver getUserIdentifierResolver() {
        return userIdentifierResolver;
    }

    public static void setCommunicationDataStore(CommunicationDataStore<TimestampedStatusResponse> dataStore) {
        communicationDataStore = dataStore;
    }

    public static CommunicationDataStore<TimestampedStatusResponse> getCommunicationDataStore() {
        return communicationDataStore;
    }

    /** {@inheritDoc} */
    public void login(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        log.debug("Starting mobile login.");
        URLBuilder urlBuilder = HttpServletHelper.getServletContextUrl(servletRequest);

        StringBuilder pathBuilder = new StringBuilder(urlBuilder.getPath());
        String servletPattern = "/Authn/MobileService";
        if (!servletPattern.startsWith("/")) {
            pathBuilder.append("/");
        }
        pathBuilder.append(servletPattern);
        urlBuilder.setPath(pathBuilder.toString());

        log.debug("Redirecting to {}", urlBuilder.buildURL());
        try {
            servletResponse.sendRedirect(urlBuilder.buildURL());
        } catch (IOException e) {
            log.error("Could not redirect to the authentication servlet", e);
        }
    }

    public static void startAuthentication(final String loginContextKey, String mobileNumber, String noSpamCode) {
        log.debug("Starting to build authentication client");
        try {
            mobileNumber = URIUtil.encodeAll(mobileNumber);
        } catch (URIException e) {
            log.warn("Could not encode the given mobile number {}", mobileNumber);
            log.debug("Stack trace for the encoding error of number {}", mobileNumber, e);
            return;
        }
        String uri = baseUrl + "/authenticate?mobileNumber=" + mobileNumber;
        if (noSpamCode != null) {
            log.debug("Included no spam code to the request");
            uri = uri + "&noSpamCode=" + noSpamCode;
        }
        log.debug("Using URI {}", uri);
        StatusResponse response = getStatusResponse(uri);
        if (response == null) {
            log.error("Could not start the mobile authentication process for {}", mobileNumber);
            return;
        }
        communicationDataStore.putData(loginContextKey, new TimestampedStatusResponse(response));
        log.debug("Authentication started for login context {}", loginContextKey);
    }

    private static HttpMethod executeUriCall(String uri) {
        log.debug("Trying to build a HTTP client");
        HttpClient httpClient = httpClientBuilder.buildClient();
        log.debug("HTTP client successfully built");
        final GetMethod getMethod = new GetMethod(uri);
        try {
            log.debug("Executing the Http method to the service");
            int status = httpClient.executeMethod(getMethod);
            if (status == 200 || status == 405) {
                log.debug("Method executed with response code {}", status);
            } else {
                log.error("Unexpected status code from the REST service: {}", status);
                return null;
            }
        } catch (HttpException e) {
            log.error("Protocol exception while connecting to " + uri, e);
            return null;
        } catch (IOException e) {
            log.error("IO exception while connecting to " + uri, e);
            return null;
        }
        return getMethod;
    }

    private static StatusResponse getStatusResponse(String uri) {
        HttpMethod httpMethod = executeUriCall(uri);
        if (httpMethod == null) {
            log.debug("Could not execute call to URL {}", uri);
            return null;
        }
        try {
            InputStream content = httpMethod.getResponseBodyAsStream();
            ObjectMapper objectMapper = new ObjectMapper();
            StatusResponse response = objectMapper.readValue(content, StatusResponse.class);
            content.close();
            log.debug("Status response eventId={}, errorMessage={}", response.getEventId(),
                    response.getErrorMessage());
            return response;
        } catch (IOException e) {
            log.error("Could not obtain response from the REST service!", e);
            return null;
        } finally {
            httpMethod.releaseConnection();
        }
    }

    private static StatusResponse getStatusUpdate(String loginContextKey) {
        if (communicationDataStore.containsKey(loginContextKey)) {
            String communicationDataKey = communicationDataStore.getData(loginContextKey).getCommunicationDataKey();
            String uri = baseUrl + "/getStatus?communicationDataKey=" + communicationDataKey;
            StatusResponse statusResponse = getStatusResponse(uri);
            if (statusResponse != null) {
                log.debug("Updating the response for login context {}", loginContextKey);
                TimestampedStatusResponse oldStatusResponse = communicationDataStore.getData(loginContextKey);
                oldStatusResponse.setAttributes(statusResponse.getAttributes());
                oldStatusResponse.setErrorMessage(statusResponse.getErrorMessage());
                communicationDataStore.putData(loginContextKey, oldStatusResponse);
                return statusResponse;
            }
        }
        log.debug("No existing entry for {}", loginContextKey);
        return null;
    }

    public static boolean isRequestInProcess(String loginContextKey) {
        log.debug("Verifying the state for {}", loginContextKey);
        StatusResponse statusResponse = getStatusUpdate(loginContextKey);
        if (statusResponse != null) {
            return statusResponse.getAttributes() == null && statusResponse.getErrorMessage() == null;
        }
        return false;
    }

    public static Subject getResponse(String loginContextKey) {
        if (communicationDataStore.containsKey(loginContextKey)) {
            Map<String, String> attributes = communicationDataStore.getData(loginContextKey).getAttributes();
            if (attributes == null) {
                log.warn("No response attributes found for {} to be returned", loginContextKey);
                return null;
            }
            log.debug("List of attributes size {}", attributes.size());
            final Subject userSubject = new Subject();
            String mobileNumber = attributes.get(StatusResponse.ATTRIBUTE_ID_MSISDN);
            if (mobileNumber == null) {
                log.warn("Could not obtain mobile number from the response attributes for {}", loginContextKey);
                return null;
            }
            String hookAttribute = DatatypeHelper
                    .safeTrimOrNullString(attributes.get(userIdentifierResolver.getHookAttributeName()));
            if (hookAttribute == null) {
                log.debug("Populating the attributes to the Principal objects");
                return populatePrincipals(userSubject, attributes, mobileNumber);
            }
            String username = userIdentifierResolver.getUserIdentifier(hookAttribute);
            log.debug("Resolved username {} to mobile number {}", username, mobileNumber);
            if (username != null) {
                userSubject.getPrincipals().add(new UsernamePrincipal(username));
            } else {
                userSubject.getPrincipals().add(new MobileNumberPrincipal(mobileNumber));
            }
            return userSubject;
        }
        log.warn("No data stored for {}, could not return response object", loginContextKey);
        return null;
    }

    protected static final Subject populatePrincipals(final Subject subject, final Map<String, String> attributes,
            String mobileNumber) {
        String age = DatatypeHelper.safeTrimOrNullString(attributes.get(FiComConstants.PERSON_AGE));
        String givenName = DatatypeHelper.safeTrimOrNullString(attributes.get(FiComConstants.PERSON_GIVENNAME));
        String hetu = DatatypeHelper.safeTrimOrNullString(attributes.get(FiComConstants.PERSON_HETU));
        String satu = DatatypeHelper.safeTrimOrNullString(attributes.get(FiComConstants.PERSON_SATU));
        String surname = DatatypeHelper.safeTrimOrNullString(attributes.get(FiComConstants.PERSON_SURNAME));

        if (age != null) {
            log.debug("Populating the age={} to the session", age);
            subject.getPrincipals().add(new FiComAgePrincipal(age));
        }
        if (givenName != null) {
            log.debug("Populating the givenName={} to the session", givenName);
            subject.getPrincipals().add(new FiComGivenNamePrincipal(givenName));
        }
        if (hetu != null) {
            log.debug("Populating the hetu to the session");
            subject.getPrincipals().add(new FiComHetuPrincipal(hetu));
        }
        if (satu != null) {
            log.debug("Populating the satu to the session", age);
            subject.getPrincipals().add(new FiComSatuPrincipal(satu));
        }
        if (surname != null) {
            log.debug("Populating the surname={} to the session", surname);
            subject.getPrincipals().add(new FiComSurNamePrincipal(surname));
        }

        subject.getPrincipals().add(new MobileNumberPrincipal(mobileNumber));

        log.debug("Principals populated to the session.");
        return subject;
    }

    public static String getErrorMessage(String loginContextKey) {
        if (communicationDataStore.containsKey(loginContextKey)) {
            return communicationDataStore.getData(loginContextKey).getErrorMessage();
        }
        log.warn("No data stored for {}, could not return error message", loginContextKey);
        return null;
    }

    public static void removeResponse(String loginContextKey) {
        communicationDataStore.removeData(loginContextKey);
    }

    public static String getEventId(String loginContextKey) {
        if (communicationDataStore.containsKey(loginContextKey)) {
            return communicationDataStore.getData(loginContextKey).getEventId();
        }
        log.warn("No data stored for {}, could not return event identifier", loginContextKey);
        return null;
    }
}