at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser.java Source code

Java tutorial

Introduction

Here is the source code for at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser.java

Source

/*******************************************************************************
 * Copyright 2014 Federal Chancellery Austria
 * MOA-ID has been developed in a cooperation between BRZ, the Federal
 * Chancellery Austria - ICT staff unit, and Graz University of Technology.
 * 
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
 * the European Commission - subsequent versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 * http://www.osor.eu/eupl/
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 * 
 * This product combines work with different licenses. See the "NOTICE" text
 * file for details on the various modules and licenses.
 * The "NOTICE" text file is part of the distribution. Any derivative works
 * that you distribute must include a readable copy of the "NOTICE" text file.
 ******************************************************************************/
package at.gv.egovernment.moa.id.auth.parser;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;

import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
import at.gv.egovernment.moa.id.commons.db.dao.config.TemplateType;
import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider;
import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
import at.gv.egovernment.moa.id.moduls.IRequest;
import at.gv.egovernment.moa.id.moduls.RequestStorage;
import at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol;
import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
import at.gv.egovernment.moa.logging.Logger;
import at.gv.egovernment.moa.util.BoolUtils;
import at.gv.egovernment.moa.util.FileUtils;
import at.gv.egovernment.moa.util.MiscUtil;
import at.gv.egovernment.moa.util.StringUtils;
import at.gv.egovernment.moa.util.URLEncoder;

public class StartAuthentificationParameterParser implements MOAIDAuthConstants {

    public static void parse(AuthenticationSession moasession, String target, String oaURL, String bkuURL,
            String templateURL, String useMandate, String ccc, String module, String action, HttpServletRequest req)
            throws WrongParametersException, MOAIDException {

        String targetFriendlyName = null;

        //       String sso = req.getParameter(PARAM_SSO);

        // escape parameter strings
        target = StringEscapeUtils.escapeHtml(target);
        //oaURL = StringEscapeUtils.escapeHtml(oaURL);
        bkuURL = StringEscapeUtils.escapeHtml(bkuURL);
        templateURL = StringEscapeUtils.escapeHtml(templateURL);
        useMandate = StringEscapeUtils.escapeHtml(useMandate);
        ccc = StringEscapeUtils.escapeHtml(ccc);
        //       sso = StringEscapeUtils.escapeHtml(sso);

        // check parameter

        //pvp2.x can use general identifier (equals oaURL in SAML1)
        //      if (!ParamValidatorUtils.isValidOA(oaURL))
        //           throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12");

        if (!ParamValidatorUtils.isValidUseMandate(useMandate))
            throw new WrongParametersException("StartAuthentication", PARAM_USEMANDATE, "auth.12");
        if (!ParamValidatorUtils.isValidCCC(ccc))
            throw new WrongParametersException("StartAuthentication", PARAM_CCC, "auth.12");
        //       if (!ParamValidatorUtils.isValidUseMandate(sso))
        //            throw new WrongParametersException("StartAuthentication", PARAM_SSO, "auth.12");

        //check UseMandate flag
        String useMandateString = null;
        boolean useMandateBoolean = false;
        if ((useMandate != null) && (useMandate.compareTo("") != 0)) {
            useMandateString = useMandate;
        } else {
            useMandateString = "false";
        }

        if (useMandateString.compareToIgnoreCase("true") == 0)
            useMandateBoolean = true;
        else
            useMandateBoolean = false;

        moasession.setUseMandate(useMandateString);

        //load OnlineApplication configuration
        OAAuthParameter oaParam;
        if (moasession.getPublicOAURLPrefix() != null) {
            Logger.debug("Loading OA parameters for PublicURLPrefix: " + moasession.getPublicOAURLPrefix());
            oaParam = AuthConfigurationProvider.getInstance()
                    .getOnlineApplicationParameter(moasession.getPublicOAURLPrefix());

            if (oaParam == null)
                throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() });

        } else {
            oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oaURL);

            if (oaParam == null)
                throw new AuthenticationException("auth.00", new Object[] { oaURL });

            // get target and target friendly name from config
            String targetConfig = oaParam.getTarget();
            String targetFriendlyNameConfig = oaParam.getTargetFriendlyName();

            if (StringUtils.isEmpty(targetConfig)
                    || (module.equals(SAML1Protocol.PATH) && !StringUtils.isEmpty(target))) {
                //INFO: ONLY SAML1 legacy mode
                // if SAML1 is used and target attribute is given in request
                // use requested target
                // check target parameter
                if (!ParamValidatorUtils.isValidTarget(target)) {
                    Logger.error("Selected target is invalid. Using target: " + target);
                    throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12");
                }

            } else {
                // use target from config                
                target = targetConfig;
                targetFriendlyName = targetFriendlyNameConfig;
            }

            //         //check useSSO flag
            //         String useSSOString = null;
            //         boolean useSSOBoolean = false;
            //         if ((sso != null) && (sso.compareTo("") != 0)) {
            //            useSSOString = sso;
            //         } else {
            //            useSSOString = "false";
            //         }
            //
            //         if (useSSOString.compareToIgnoreCase("true") == 0)
            //            useSSOBoolean = true;
            //         else
            //            useSSOBoolean = false;

            //moasession.setSsoRequested(useSSOBoolean);
            moasession.setSsoRequested(true && oaParam.useSSO()); //make always SSO if OA requested it!!!!

            //Validate BKU URI
            List<String> allowedbkus = oaParam.getBKUURL();
            allowedbkus.addAll(AuthConfigurationProvider.getInstance().getDefaultBKUURLs());
            if (!ParamValidatorUtils.isValidBKUURI(bkuURL, allowedbkus))
                throw new WrongParametersException("StartAuthentication", PARAM_BKU, "auth.12");

            moasession.setBkuURL(bkuURL);

            if ((!oaParam.getBusinessService())) {
                if (isEmpty(target))
                    throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.05");

            } else {
                if (useMandateBoolean) {
                    Logger.error("Online-Mandate Mode for business application not supported.");
                    throw new AuthenticationException("auth.17", null);
                }
                target = null;
                targetFriendlyName = null;
            }

            moasession.setPublicOAURLPrefix(oaParam.getPublicURLPrefix());

            moasession.setTarget(target);
            moasession.setBusinessService(oaParam.getBusinessService());
            //moasession.setStorkService(oaParam.getStorkService());
            Logger.debug(
                    "Business: " + moasession.getBusinessService() + " stork: " + moasession.getStorkService());
            moasession.setTargetFriendlyName(targetFriendlyName);
            moasession.setDomainIdentifier(oaParam.getIdentityLinkDomainIdentifier());
        }

        //check OnlineApplicationURL
        if (isEmpty(oaURL))
            throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.05");
        moasession.setOAURLRequested(oaURL);

        //check AuthURL
        String authURL = req.getScheme() + "://" + req.getServerName();
        if ((req.getScheme().equalsIgnoreCase("https") && req.getServerPort() != 443)
                || (req.getScheme().equalsIgnoreCase("http") && req.getServerPort() != 80)) {
            authURL = authURL.concat(":" + req.getServerPort());
        }
        authURL = authURL.concat(req.getContextPath() + "/");

        if (!authURL.startsWith("https:"))
            throw new AuthenticationException("auth.07", new Object[] { authURL + "*" });

        //set Auth URL from configuration
        moasession.setAuthURL(AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/");

        //check and set SourceID
        if (oaParam.getSAML1Parameter() != null) {
            String sourceID = oaParam.getSAML1Parameter().getSourceID();
            if (MiscUtil.isNotEmpty(sourceID))
                moasession.setSourceID(sourceID);
        }

        if (MiscUtil.isEmpty(templateURL)) {

            List<TemplateType> templateURLList = oaParam.getTemplateURL();
            List<String> defaulTemplateURLList = AuthConfigurationProvider.getInstance().getSLRequestTemplates();

            if (templateURLList != null && templateURLList.size() > 0
                    && MiscUtil.isNotEmpty(templateURLList.get(0).getURL())) {
                templateURL = FileUtils.makeAbsoluteURL(oaParam.getTemplateURL().get(0).getURL(),
                        AuthConfigurationProvider.getInstance().getRootConfigFileDir());
                Logger.info("No SL-Template in request, load SL-Template from OA configuration (URL: " + templateURL
                        + ")");

            } else if ((defaulTemplateURLList.size() > 0) && MiscUtil.isNotEmpty(defaulTemplateURLList.get(0))) {
                templateURL = FileUtils.makeAbsoluteURL(defaulTemplateURLList.get(0),
                        AuthConfigurationProvider.getInstance().getRootConfigFileDir());
                Logger.info("No SL-Template in request, load SL-Template from general configuration (URL: "
                        + templateURL + ")");

            } else {
                Logger.error("NO SL-Tempalte found in OA config");
                throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12");

            }

        }

        if (!ParamValidatorUtils.isValidTemplate(req, templateURL, oaParam.getTemplateURL()))
            throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12");
        moasession.setTemplateURL(templateURL);

        moasession.setCcc(ccc);

    }

    public static void parse(HttpServletRequest req, HttpServletResponse resp, AuthenticationSession moasession,
            IRequest request) throws WrongParametersException, MOAIDException {

        String modul = request.requestedModule();//req.getParameter(PARAM_MODUL);
        String action = request.requestedAction();//req.getParameter(PARAM_ACTION);

        modul = StringEscapeUtils.escapeHtml(modul);
        action = StringEscapeUtils.escapeHtml(action);
        if (modul == null) {
            modul = SAML1Protocol.PATH;
        }

        if (action == null) {
            action = SAML1Protocol.GETARTIFACT;
        }
        moasession.setModul(modul);
        moasession.setAction(action);

        //get Parameters from request
        String target = req.getParameter(PARAM_TARGET);
        String oaURL = req.getParameter(PARAM_OA);
        String bkuURL = req.getParameter(PARAM_BKU);
        String templateURL = req.getParameter(PARAM_TEMPLATE);
        String useMandate = req.getParameter(PARAM_USEMANDATE);
        String ccc = req.getParameter(PARAM_CCC);

        oaURL = request.getOAURL();
        target = request.getTarget();

        parse(moasession, target, oaURL, bkuURL, templateURL, useMandate, ccc, modul, action, req);

    }

    /**
     * Checks a parameter.
     * 
     * @param param
     *            parameter
     * @return true if the parameter is null or empty
     */
    private static boolean isEmpty(String param) {
        return param == null || param.length() == 0;
    }
}