Class HttpUtil

  • All Implemented Interfaces:
    JcmsConstants, JaliosConstants

    public class HttpUtil
    extends java.lang.Object
    implements JcmsConstants
    This class contains a set of static utility methods for validation, encoding and decoding of http and html input/output.
    • Constructor Detail

      • HttpUtil

        public HttpUtil()
    • Method Detail

      • encodeForXML

        public static java.lang.String encodeForXML​(java.lang.String input)
        Encode data for use in an XML element. The implementation should follow the XML Encoding Standard from the W3C.

        The use of a real XML parser is strongly encouraged. However, in the hopefully rare case that you need to make sure that data is safe for inclusion in an XML document and cannot use a parse, this method provides a safe mechanism to do so.

        Parameters:
        input - the text to encode for XML
        Returns:
        input encoded for XML, return empty string if null was specified as input parameter
        See Also:
        XML Encoding Standard
      • encodeForXMLAttribute

        public static java.lang.String encodeForXMLAttribute​(java.lang.String input)
        Encode data for use in an XML attribute. The implementation should follow the XML Encoding Standard from the W3C.

        The use of a real XML parser is highly encouraged. However, in the hopefully rare case that you need to make sure that data is safe for inclusion in an XML document and cannot use a parse, this method provides a safe mechanism to do so.

        Parameters:
        input - the text to encode for use as an XML attribute
        Returns:
        input encoded for XML attribute, return empty string if null was specified as input parameter
        See Also:
        XML Encoding Standard
      • encodeForHTML

        public static java.lang.String encodeForHTML​(java.lang.String input)
        Encode data for use in HTML using HTML entity encoding

        Note that the following characters: 00-08, 0B-0C, 0E-1F, and 7F-9F

        cannot be used in HTML.

        Parameters:
        input - the text to encode for HTML
        Returns:
        input encoded for HTML, return empty string if null was specified as input parameter
        See Also:
        HTML Encodings [wikipedia.org], SGML Specification [w3.org], XML Specification [w3.org]
      • encodeForHTMLAttribute

        public static java.lang.String encodeForHTMLAttribute​(java.lang.String input)
        Encode data for use in HTML attributes.
        Parameters:
        input - the text to encode for an HTML attribute
        Returns:
        input encoded for use as an HTML attribute, return empty string if null was specified as input parameter
      • encodeForHTMLAttribute

        public static java.lang.String encodeForHTMLAttribute​(java.lang.String input,
                                                              boolean unescapeHTML)
        Encode data for use in HTML attributes, optionally unescaping the HTML before the encoding.

        Unescaping the HTML is needed when working with text value stored inside JCMS Data. Indeed, text entered by the user is escaped using JcmsUtil.escapeHtml(String) prior being saved in the Data fields, thus in order to display the text exactly as entered by the user, unescaping the input using JcmsUtil.unescapeHtml(String) is necessary.

        Example :

           <span title="<%= encodeForHTMLAttribute(data.getTitle(userLang), true) %>">...</span>
         
           <span title="<%= encodeForHTMLAttribute(glp("..."), false) %>">...</span>
         
        Parameters:
        input - the text to encode for an HTML attribute
        unescapeHTML - set to true to unescape HTML PRIOR to HTML attribute encoding, set to false to only perform HTML attribute encoding.
        Returns:
        input encoded for use as an HTML attribute, return empty string if null was specified as input parameter
        Since:
        jcms-9.0
      • encodeForJavaScript

        public static java.lang.String encodeForJavaScript​(java.lang.String input)
        Encode data for insertion inside a data value or function argument in JavaScript. Including user data directly inside a script is quite dangerous. Great care must be taken to prevent including user data directly into script code itself, as no amount of encoding will prevent attacks there. Please note there are some JavaScript functions that can never safely receive untrusted data as input – even if the user input is encoded. For example: <script> window.setInterval('<%= EVEN IF YOU ENCODE UNTRUSTED DATA YOU ARE XSSED HERE %>'); </script>
        Parameters:
        input - the text to encode for JavaScript
        Returns:
        input encoded for use in JavaScript, return empty string if null was specified as input parameter
      • encodeForURL

        public static java.lang.String encodeForURL​(java.lang.String input)
        Encode for use in a URL. This method performs URL encoding on the entire string.
        Parameters:
        input - the text to encode for use in a URL
        Returns:
        input encoded for use in a URL, return empty string if null was specified as input parameter
        See Also:
        URL encoding
      • addAttachmentHeader

        public static void addAttachmentHeader​(javax.servlet.http.HttpServletResponse response,
                                               java.lang.String filename)
        Add the Content-Disposition HTTP header and attachement parameter field to specify which name to use on remote client when downloading a file.
        Parameters:
        response - the HttpServletResponse in which to send the header, if null method returns immediately
        filename - the name of the file to use on remote client, if null or empty value method return immediately
        Since:
        8.0.3 / 9.0.1 - JCMS-4395
      • addAttachmentHeader

        public static void addAttachmentHeader​(javax.servlet.http.HttpServletResponse response,
                                               java.lang.String filename,
                                               boolean forceDownload)
        Add the Content-Disposition HTTP header and attachement parameter field to specify which name to use on remote client when downloading a file.
        Parameters:
        response - the HttpServletResponse in which to send the header, if null method returns immediately
        filename - the name of the file to use on remote client, if null or empty value method return immediately
        forceDownload - if true add "attachment" in the header value to force the download
        Since:
        10.0.8
      • getValidHttpUrl

        public static java.lang.String getValidHttpUrl​(javax.servlet.http.HttpServletRequest request,
                                                       java.lang.String parameterName)
        Retrieve a verified URL parameter value.

        Example :

         String redirect = getValidHttpUrl(request, "redirect");
         
        Parameters:
        request - the request from which the parameter will be read
        parameterName - the name of the HTTP parameter to be retrieved
        Returns:
        the URL or null if parameter was missing or received URL was invalid
      • validateHttpUrl

        public static java.lang.String validateHttpUrl​(java.lang.String url)
        Validate an URL and returns it.

        Example :

         String redirect = validateHttpUrl("http://www.example.com/");
         
        Parameters:
        url - the value to be verified
        Returns:
        the URL or null if URL was invalid
      • isValidHttpUrl

        public static boolean isValidHttpUrl​(java.lang.String url)
        Check that the specified URL (absolute or relative) is a valid URL authorized for use in redirection.

        As of current implementation, the following behavior applies : All URLs are accepted (NO verification performed) when JCMS propery channel.security.validate-redirect is set to false (default is true).

        Otherwise, the following rules are required :

        • URLs must not exceed 2000 characters
        • URLs must match dedicated regex property JCMSRedirectURL configured in ESAPI.properties (prevent HTTPSplitting)
        And the following validation is performed :
        • Relative URLs are always accepted
        • URLs starting with site's base URL are accepted
        • URLs starting with base URL of current servlet request are accepted
        • URLs starting with any active configuration of reverse proxy's base URL are accepted (http or https)
        • URLs matching any regex configured in JCMS properties channel.security.authorized-redirect.* are accepted
        • Other URLs are rejected

        You can enable TRACE logging on this class for detailed information of validation being performed.

         <logger name="com.jalios.jcms.HttpUtil"> <level value="TRACE" /> </logger>
         
        Parameters:
        url - the URL to check
        Returns:
        true if a redirect can be perform with this URL, false otherwise
      • authorizeUrl

        public static void authorizeUrl​(java.lang.String id,
                                        java.lang.String url,
                                        boolean prefix)
        Authorize the specified URL in URL validation check.

        Use this method to authorize redirect to external trusted site, which are dynamically declared (e.g. SSO).

        The authorization is voluntarly NOT saved upon restart.
        Invoke this method each time the configuration changes, with its corresponding removal method unauthorizeUrl(String).

        Parameters:
        id - a unique identifier to identify the URL being added, must no be null
        url - the URL prefix to add authorized, must no be null
        prefix - true to authorized all URL prefixed with specified value, false to authorized only this exact URL
        Since:
        10.0.8 / JCMS-10400
        See Also:
        unauthorizeUrl(String), isValidHttpUrl(String)
      • unauthorizeUrl

        public static void unauthorizeUrl​(java.lang.String id)
        Unauthorized a previously registered URL from URL validation check, by specifying the identifier that was used when authorized.

        Use this method to unauthorize a URL when the configuration changes.

        Parameters:
        id - the unique identifier that was used in authorizeUrl(String, String, boolean) to identify the authorized URL, must no be null
        Since:
        10.0.8 / JCMS-10400
        See Also:
        authorizeUrl(String, String, boolean), isValidHttpUrl(String)
      • isValidDisplayServletPath

        public static boolean isValidDisplayServletPath​(java.lang.String displayServletPath)
        Check if the specified path is valid for use by the display servlet
        Parameters:
        displayServletPath - a servlet path such as "/jcms/c_42/foo-bar"
        Returns:
        true if the path is valid, false otherwise
      • isValidAgainstRegex

        public static boolean isValidAgainstRegex​(java.lang.String context,
                                                  java.lang.String property,
                                                  java.lang.String input)
        Check the specified input match the regex defined in specified property
        Parameters:
        context - a context used for logging if validation fails
        property - the name of a propery in which regexp is retrieved
        input - the input to check
        Returns:
        true if input validate the regexp, false otherwise
        Since:
        jcms-10.0.0 / JCMS-5568 (public since 10.0.8 / JCMS-10963)
      • getChooserParameter

        public static java.lang.String getChooserParameter​(javax.servlet.http.HttpServletRequest request,
                                                           java.lang.String parameterName)
        Retrieve a verified targetInput, targetLabel or other target value used by JCMS Choosers inside javascript code.

        Example :

         String targetInput = getChooserParameter("targetInput");
         String targetLabel = getChooserParameter("targetLabel");
         
        Parameters:
        request - HttpServletRequest from which parameter must be read
        parameterName - the name of the HTTP parameter to be retrieved
        Returns:
        a valid and sanitized target (input, label, ...) or null if parameter was missing or invalid
      • getDataParameter

        public static <T> T getDataParameter​(javax.servlet.http.HttpServletRequest request,
                                             java.lang.String parameterName,
                                             java.lang.Class<T> clazz)
        Retrieve a typed Data from its id received in parameter.

        Examples :

         Portal portal = getDataParameter(request, "portal", Portal.class);
         SmallNews sm = getDataParameter(request, "id", SmallNews.class);
         
        Type Parameters:
        T - the expected class of Data
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data id will be retrieved, must not be null
        clazz - the expected class of Data
        Returns:
        the Data corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
      • getDataListParameter

        public static <T extends Data> java.util.List<T> getDataListParameter​(javax.servlet.http.HttpServletRequest request,
                                                                              java.lang.String parameterName,
                                                                              java.lang.Class<T> clazz)
        Retrieve a list of Data from ids received in only one value of the parameter (seperated with spaces or coma).

        Examples :

         List<Group> groupList = getDataListParameter(request, "groups", Portal.class);
         SmallNews sm = getDataParameter(request, "id", SmallNews.class);
         
        Type Parameters:
        T - the expected class of Data
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data ids will be retrieved, must not be null
        clazz - the expected class of Data
        Returns:
        the List of Data, corresponding to the ids received in parameter or empty list if parameter was missing, empty or invalid
      • getDataParameter

        public static Data getDataParameter​(javax.servlet.http.HttpServletRequest request,
                                            java.lang.String parameterName)
        Retrieve a Data from its id received in parameter.

        Example :

         Data data = getDataParameter(request, "id");
         
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data id will be retrieved, must not be null
        Returns:
        the Data corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
      • getWorkspaceParameter

        public static Workspace getWorkspaceParameter​(javax.servlet.http.HttpServletRequest request,
                                                      java.lang.String parameterName)
        Retrieve a Workspace from its id received in parameter.

        Example :

         Workspace ws = getWorkspaceParameter(request, "ws");
         
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data id will be retrieved, must not be null
        Returns:
        the Workspace corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
      • getCategoryParameter

        public static Category getCategoryParameter​(javax.servlet.http.HttpServletRequest request,
                                                    java.lang.String parameterName)
        Retrieve a Category from its id received in parameter.

        Example :

         Category cat = getCategoryParameter(request, "cid");
         
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data id will be retrieved, must not be null
        Returns:
        the Category corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
      • getPublicationParameter

        public static Publication getPublicationParameter​(javax.servlet.http.HttpServletRequest request,
                                                          java.lang.String parameterName)
        Retrieve a Publication from its id received in parameter.

        Example :

         Publication pub = getPublicationParameter(request, "id");
         
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data id will be retrieved, must not be null
        Returns:
        the Publication corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
      • getMemberParameter

        public static Member getMemberParameter​(javax.servlet.http.HttpServletRequest request,
                                                java.lang.String parameterName)
        Retrieve a Member from its id received in parameter.

        Example :

         Member mbr = getMemberParameter(request, "mbrId");
         
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data id will be retrieved, must not be null
        Returns:
        the Member corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
      • getGroupParameter

        public static Group getGroupParameter​(javax.servlet.http.HttpServletRequest request,
                                              java.lang.String parameterName)
        Retrieve a Group from its id received in parameter.

        Example :

         Group grp = getGroupParameter(request, "grpId");
         
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data id will be retrieved, must not be null
        Returns:
        the Group corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
      • hasParameter

        public static boolean hasParameter​(javax.servlet.http.HttpServletRequest request,
                                           java.lang.String parameterName)
        Check if a parameter was received in the specified request.

        Example :

         if (hasParameter(request, "opRefresh")) {
         //...
         }
         
        This method is the same as doing :
         String value = getUntrustedStringParameter(request, parameterName); // request.getParameter(parameterName);
         return value != null;
         
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        Returns:
        false if parameter was not in the request (null value) true in any other case
      • getBooleanParameter

        public static boolean getBooleanParameter​(javax.servlet.http.HttpServletRequest request,
                                                  java.lang.String parameterName,
                                                  boolean defaultValue)
        Retrieve a boolean value from specified HTTP request parameter.

        Important remark regarding behavior on missing/invalid parameter :

        • Use the specified defaultValue if parameter is missing (null).
        • Always returns false when parameter value contains invalid data (neither "true" nor "false").
        This is the same behavior applied by method Util.toBoolean(Object, boolean).
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        defaultValue - the default value to use if parameter is missing or invalid
        Returns:
        a boolean value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing or invalid
      • getIntParameter

        public static int getIntParameter​(javax.servlet.http.HttpServletRequest request,
                                          java.lang.String parameterName,
                                          int defaultValue)
        Retrieve an integer value from specified HTTP request parameter.
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        defaultValue - the default value to use if parameter is missing or invalid
        Returns:
        an integer value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing or invalid
      • getLongParameter

        public static long getLongParameter​(javax.servlet.http.HttpServletRequest request,
                                            java.lang.String parameterName,
                                            long defaultValue)
        Retrieve a long value from specified HTTP request parameter.
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        defaultValue - the default value to use if parameter is missing, empty or invalid
        Returns:
        a long value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
      • getDoubleParameter

        public static double getDoubleParameter​(javax.servlet.http.HttpServletRequest request,
                                                java.lang.String parameterName,
                                                double defaultValue)
        Retrieve a double value from specified HTTP request parameter.
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        defaultValue - the default value to use if parameter is missing, empty or invalid
        Returns:
        a double value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
      • getDateTimeParameter

        public static java.util.Date getDateTimeParameter​(javax.servlet.http.HttpServletRequest request,
                                                          java.lang.String parameterName,
                                                          java.lang.String dateLanguage,
                                                          java.util.Date defaultValue)
        Retrieve a Date (date and time) value from specified HTTP request parameter.

        The parameter will be parsed using date format specified in property date-time-format of the specified language.

        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be parsed, must not be null
        dateLanguage - the language in which the received parameter will be parsed
        defaultValue - the default value to use if parameter is missing, empty or invalid
        Returns:
        a Date value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
        See Also:
        Channel.getDateTimeFormat(String)
      • getDateParameter

        public static java.util.Date getDateParameter​(javax.servlet.http.HttpServletRequest request,
                                                      java.lang.String parameterName,
                                                      java.lang.String dateLanguage,
                                                      java.util.Date defaultValue)
        Retrieve a Date (date only) value from specified HTTP request parameter.

        The parameter will be parsed using date format specified in property date-format of the specified language.

        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be parsed, must not be null
        dateLanguage - the language in which the received parameter will be parsed
        defaultValue - the default value to use if parameter is missing, empty or invalid
        Returns:
        a Date value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
        See Also:
        Channel.getDateFormat(String)
      • getDateParameter

        public static java.util.Date getDateParameter​(javax.servlet.http.HttpServletRequest request,
                                                      java.lang.String parameterName,
                                                      java.text.DateFormat dateFormat,
                                                      java.util.Date defaultValue)
        Retrieve a Date value from specified HTTP request parameter.

        The parameter will be parsed using the specified date format

        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be parsed, must not be null
        dateFormat - the DateFormat to use to parse the date parameter, must not be null
        defaultValue - the default value to use if parameter is missing, empty or invalid
        Returns:
        a Date value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
        See Also:
        Channel.getDateFormat(String)
      • getStringEnumParameter

        public static java.lang.String getStringEnumParameter​(javax.servlet.http.HttpServletRequest request,
                                                              java.lang.String parameterName,
                                                              java.lang.String defaultValue,
                                                              java.lang.String... possibleValues)
        Retrieve a String value from specified HTTP request parameter.

        The parameter value must match one of the possible value specified, otherwise default value is used.

        Example, read the "align" parameter expecting only values from authorized HTML table align :

         getStringEnumParameter(request, "align", "left", new String[] { "left", "center", "right" });
         
        Verification is case sensitive.
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        defaultValue - the default value to use if parameter is missing or invalid
        possibleValues - the values authorized, must not be null
        Returns:
        a String value, or the default value if parameter was missing or invalid (did not match any possible value)
      • getAlphaNumParameter

        public static java.lang.String getAlphaNumParameter​(javax.servlet.http.HttpServletRequest request,
                                                            java.lang.String parameterName,
                                                            java.lang.String defaultValue)
        Retrieve a String value from specified HTTP request parameter.

        The parameter value must match the alpha numeric regular expression ALPHANUM_REGEX.

        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        defaultValue - the default value to use if parameter is missing or invalid
        Returns:
        a String value, or the default value if parameter was missing or invalid (did not match regex)
      • getDataIdParameter

        public static java.lang.String getDataIdParameter​(javax.servlet.http.HttpServletRequest request,
                                                          java.lang.String parameterName)
        Retrieve a Data id from parameter.

        Contrary to most get*Parameter method in HttpUtil, this method returns an empty string if parameter value was missing, empty or invalid.

        Beware that this method will NOT check that the id match an existing or valid data.

        Example :

         In Java : String id = HttpUtil.getDataIdParameter(request, "id");
         In JSP : <input name="id" value="<%= getDataIdParameter("id") %>"/>
         
        This method is the same as doing :
         String id = HttpUtil.getStringParameter(request, parameterName, "", HttpUtil.DATAID_REGEX);
         
        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - the name of the HTTP parameter from which data id will be retrieved, must not be null
        Returns:
        an id, or an empty string if parameter was missing, empty or invalid (never returns null)
      • getStringParameter

        public static java.lang.String getStringParameter​(javax.servlet.http.HttpServletRequest request,
                                                          java.lang.String parameterName,
                                                          java.lang.String defaultValue,
                                                          java.lang.String regex)
        Retrieve a String value from specified HTTP request parameter.

        The parameter value must match the specified regular expression.

        You are encouraged to use predefined constants for regular expression :

        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        defaultValue - the default value to use if parameter is missing or invalid
        regex - the regular expression the string is expected to match, must not be null
        Returns:
        a String value, or the default value if parameter was missing or invalid (did not match regex)
      • validateString

        public static java.lang.String validateString​(java.lang.String value,
                                                      java.lang.String regex)
        Validate a String value against specified regular expression.

        You are encouraged to use predefined constants for regular expression :

        Parameters:
        value - value to validate
        regex - the regular expression the string is expected to matchn, must not be null
        Returns:
        a String value, or null if specified value was null or invalid (did not match regex)
      • getStringParameterValues

        public static java.lang.String[] getStringParameterValues​(javax.servlet.http.HttpServletRequest request,
                                                                  java.lang.String parameterName,
                                                                  java.lang.String regex)
        Retrieve array of String values from specified HTTP request parameter.

        The parameter values must match the specified regular expression.

        You are encouraged to use predefined constants for regular expression :

        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        regex - the regular expression strings are expected to match, must not be null
        Returns:
        an array of String values, null if parameter was missing, empty or partial array when all or some values were invalid (did not match regex)
      • validateStringValues

        public static java.lang.String[] validateStringValues​(java.lang.String[] values,
                                                              java.lang.String regex)
        Validate each value in the specified array of String values against specified regular expression.

        You are encouraged to use predefined constants for regular expression :

        Parameters:
        values - the values to validate
        regex - the regular expression strings are expected to match, must not be null
        Returns:
        an array of String values, null if specified values array was null. Returns an empty or partial array when all or some values were invalid (did not match regex)
      • getUntrustedStringParameter

        public static java.lang.String getUntrustedStringParameter​(javax.servlet.http.HttpServletRequest request,
                                                                   java.lang.String parameterName,
                                                                   java.lang.String defaultValue)
        Retrieve any String value from the specified HTTP request parameter.

        This method should be AVOIDED AT ALL COST, and used only on last restort, make sure you PROPERLY ENCODE the returned value in the output..

        Parameters:
        request - HttpServletRequest from which parameter must be read, must not be null
        parameterName - name of the HTTP parameter from which value will be read, must not be null
        defaultValue - the default value to use if parameter is missing
        Returns:
        a String value, or the default value if parameter was missing or an empty string
      • addCookie

        public static void addCookie​(javax.servlet.http.HttpServletResponse response,
                                     javax.servlet.http.Cookie cookie)
        Add a cookie to the response.

        This method provides the following security check :

        • Ensure that there are no encoded or illegal characters in the cookie's name and value (if invalid character are used, cookie is not added to response).
          Authorized character can be configured in properties file using following properties :
           channel.security.Validator.HTTPCookieName: 
           channel.security.Validator.HTTPCookieValue: 
           
        • Sets the secure and HttpOnly flags on the cookie according to properties configuration.
           channel.security.HttpUtilities.ForceHttpOnlyCookies: true
           channel.security.HttpUtilities.ForceSecureCookies: true
           
        Parameters:
        response - the HttpServletResponse in which to send the cookie
        cookie - the cookie to send in the response
      • addHeader

        public static void addHeader​(javax.servlet.http.HttpServletResponse response,
                                     java.lang.String name,
                                     java.lang.String value)
        Add a header to the response after ensuring that there are no encoded or illegal characters in the name and name and value. This implementation follows the following recommendation: "A recipient MAY replace any linear white space with a single SP before interpreting the field value or forwarding the message downstream." http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
        Parameters:
        response - the HttpServletResponse in which HTTP header should be added
        name - the HTTP header name to add
        value - the HTTP header value to add
        Since:
        jcms-10.0.0 / JCMS-5568
      • isCSRFEnabled

        public static boolean isCSRFEnabled()
        Check if CSRF attack prevention is enabled for site.
        Returns:
        true if CSRF prevention is enabled, false otherwise
      • getCSRFToken

        public static java.lang.String getCSRFToken​(javax.servlet.http.HttpServletRequest request)
        Retrieve the value of CSRF token (both session & member) for the current request.
        Parameters:
        request - the curren HttpServletRequest
        Returns:
        the token value or an empty string, never return null
        Since:
        jcms-7.0.4 jcms-7.1.1
      • initializeCSRFToken

        public static void initializeCSRFToken​(javax.servlet.http.HttpSession session)
        Initialize a new CSRF Token for the current session (if any)
        Parameters:
        session - the HttpSession in which CSRF token is added
      • getCurrentCSRFToken

        public static java.lang.String getCurrentCSRFToken​(javax.servlet.http.HttpSession session)
        Retrieve the current valid CSRF Token expected on critical requests of the current session.
        Parameters:
        session - the current HttpSession
        Returns:
        the expected CSRF token value
      • getCurrentCSRFToken

        public static java.lang.String getCurrentCSRFToken​(javax.servlet.http.HttpServletRequest request)
        Retrieve the current valid CSRF Token expected on critical requests of the current session.
        Parameters:
        request - the curren HttpServletRequest
        Returns:
        the expected CSRF token value
      • isCSRFMemberTokenAllowed

        public static boolean isCSRFMemberTokenAllowed()
        Check if CSRF token should be allowed through different session in order to allow a submition after session expiration.

        Initialized from property channel.security.csrf.allow-token-through-session

        If enabled, security is decreased as it allows more time for an attacker to retrieve the token, but usability increase as the end user is allowed to submit a form after session expiration.

        Returns:
        true if CSRF prevention is enabled, false otherwise
      • getCSRFMemberTokenMaxAge

        public static long getCSRFMemberTokenMaxAge()
        Retrieve the duration in milliseconds above which a member token is considered invalid.

        Initialized from property channel.security.csrf.member-token-max-age

        Returns:
        a duration in milliseconds
      • initializeMemberCSRFToken

        public static void initializeMemberCSRFToken​(Member member,
                                                     javax.servlet.http.HttpServletRequest request)
        Initialize the CSRF Token for the specified member from the current CSRF token of the request (if any)

        Parameters:
        member - the logged Member
        request - the current HttpServletRequest
      • clearMemberCSRFToken

        public static void clearMemberCSRFToken​(Member member)
        Remove CSRF token of the specified member
        Parameters:
        member - the member for which CSRF token should be removed
      • getCurrentMemberCSRFToken

        public static java.lang.String getCurrentMemberCSRFToken​(Member member)
        Retrieve the current valid CSRF Token expected on critical requests of the specified member.

        This method must be used only if "token through session" option has been enabled.

        Parameters:
        member - the current Member
        Returns:
        the expected CSRF token value, or null if none could be found
        See Also:
        isCSRFMemberTokenAllowed()
      • checkCSRF

        public static boolean checkCSRF​(javax.servlet.http.HttpServletRequest request)
        Check if the specified request is valid against CSRF attack.
        Parameters:
        request - the HttpServletRequest to validate
        Returns:
        true if the request is safe (or null), false if the request cannot be guaranteed for safety
      • getUrlWithCSRFToken

        public static java.lang.String getUrlWithCSRFToken​(java.lang.String url,
                                                           javax.servlet.http.HttpServletRequest request,
                                                           boolean escapeAmpersand)
        Adds the current CSRF token to the specified URL and returns it.

        If CSRF is disable, URL is returned as is.

        Parameters:
        url - the URL to complete
        request - the current request used to find the current CSRF token
        escapeAmpersand - will use "&amp;" if true, "&" if false
        Returns:
        a modified URL with the added CSRF token, or the unchanged specified URL if CSRF is disabled
      • getJsonParameterFromRequest

        public static java.lang.String getJsonParameterFromRequest​(javax.servlet.http.HttpServletRequest request)
        Returns a String (json format) representing all parameters in the specified request.
        Parameters:
        request - the HttpServletRequest
        Returns:
        a String (json format) representing all parameters in the request, or an empty string if the request in parameter is null or the JSON conversion failed.
        Since:
        jcms-8.0.1
      • accept

        public static boolean accept​(javax.servlet.http.HttpServletRequest request,
                                     java.lang.String mimeType)
        Check if the specified mime type can be understood by the client who emitted the specified request as specified by its Accept HTTP header.

        This methods check the "Accept" header to ensure it match the specified mime type.

        Parameters:
        request - the request in which the Accept header is being verified
        mimeType - a mime type, for example "text/html"
        Returns:
        true if client accept mime type, false in any other case (invalid request or mime type specified, missing Accept Header, Accept Header does not match mimeType)
        Since:
        jcms-10.0.0 (for JCMS-5648 and JCMS-5942)
      • getRemoteIpAddr

        public static java.lang.String getRemoteIpAddr​(javax.servlet.http.HttpServletRequest request)
        Get the remote IP of the request (with usage of XFORWARD header or attribute)
        Parameters:
        request - the HttpServletRequest
        Returns:
        the remote IP
      • getXForwardedFor

        public static java.lang.String getXForwardedFor​(javax.servlet.http.HttpServletRequest request)
        Get the x-forwarded for element of the request (with usage of XFORWARD header or attribute)
        Parameters:
        request - the HttpServletRequest
        Returns:
        the remote IP from XFORWARD header or attribute