% This LaTeX document was generated using the LaTeX backend of PlDoc,
% The SWI-Prolog documentation system



\subsection{library(http/http_cors): Enable CORS: Cross-Origin Resource Sharing}

\label{sec:httpcors}

\begin{tags}
\mtag{See also}- \url{http://en.wikipedia.org/wiki/Cross-site_scripting} for understanding
Cross-site scripting. \\- \url{http://www.w3.org/TR/cors/} for understanding CORS
\end{tags}

This small module allows for enabling Cross-Origin Resource Sharing
(CORS) for a specific request. Typically, CORS is enabled for API
services that you want to have useable from browser client code that is
loaded from another domain. An example are the LOD and SPARQL services
in ClioPatria.

Because CORS is a security risc (see references), it is disabled by
default. It is enabled through the setting http:cors. The value of this
setting is a list of domains that are allowed to access the service.
Because * is used as a wildcard match, the value [*] allows access from
anywhere.

Services for which CORS is relevant must call \predref{cors_enable}{0} as part of
the HTTP response, as shown below. Note that \predref{cors_enable}{0} is a no-op if
the setting http:cors is set to the empty list (\Snil{}).

\begin{code}
my_handler(Request) :-
      ....,
      cors_enable,
      reply_json(Response, []).
\end{code}

If a site uses a \textit{Preflight} \verb$OPTIONS$ request to find the server's
capabilities and access politics, \predref{cors_enable}{2} can be used to formulate
an appropriate reply. For example:

\begin{code}
my_handler(Request) :-
      option(method(options), Request), !,
      cors_enable(Request,
                  [ methods([get,post,delete])
                  ]),
      format('~n').                           % 200 with empty body
\end{code}

\vspace{0.7cm}

\begin{description}
    \predicate[det]{cors_enable}{0}{}
Emit the HTTP header \verb$Access-Control-Allow-Origin$ using
domains from the setting http:cors. This this setting is \Snil{}
(default), nothing is written. This predicate is typically used
for replying to API HTTP-request (e.g., replies to an AJAX
request that typically serve JSON or XML).

    \predicate[det]{cors_enable}{2}{+Request, +Options}
CORS reply to a \textit{Preflight} \verb$OPTIONS$ request. \arg{Request} is the
HTTP request. \arg{Options} provides:

\begin{description}
    \termitem{methods}{+List}
\arg{List} of supported HTTP methods. The default is \verb$GET$, only
allowing for read requests.
    \termitem{headers}{+List}
\arg{List} of headers the client asks for and we allow. The
default is to simply echo what has been requested for.
\end{description}

Both methods and headers may use Prolog friendly syntax, e.g.,
\const{get} for a method and \verb$content_type$ for a header.

\begin{tags}
    \tag{See also}
\url{http://www.html5rocks.com/en/tutorials/cors/}
\end{tags}
\end{description}

