CORS Filter 1.7 with more configuration options

CORS FilterThe Java servet filter for enabling CORS (cross-domain) web applications received a major upgrade today.

Up until now in order to change the out-of-the-box CORS configuration you had to add filter init-params in the web.xml descriptor of your application. A number of developers asked for alternative configuration means, such as specifying a properties file for the configuration. This is now supported.

The CORS Filter will now apply the following precedence when resolving the configuration:

  1. Checks for an environment variable “cors.configurationFile” pointing to a properties file with the CORS configuration.
  2. Checks for a servlet filter init-param “cors.configurationFile” pointing to a properties file with the CORS configuration.
  3. Checks for CORS params in filter init section, applies the default values if not found.

Another important configuration change is the ability to specify a general “allow-any-request-header” policy by setting the cors.supportedHeaders to an asterisk.

Handling of same-domain requests that carry a redundant Origin header (set by some Javascript frameworks) is fixed too.

Thanks to David Bellem, Stijn Cremers and Casey Lucas for initiating this new release of the CORS Filter. Also thanks to Anne van Kesteren for answering my CORS-related query on the W3C list.

Лаб Пловдив – учредителен протокол

*** Протокол на учредителната среща на Лаб Пловдив ***

16 май 2013, Арт Кафе Пловдив

записал Владимир Джувинов

Срещата започна в 18:30ч с лично представяне на всеки от участниците.

След това бяха записани предложения на участници за лаба за неговите условия,
организиране и дейности:

* Възможност за сигурно паркиране на велосипеди
* Лесно паркиране в района за автомобили
* Тиха стая за работа
* Достъп 24/7
* Нежилищно, тихо място
* Възможност за помещаване на фриланс офиси, място за работни срещи и с
клиенти, за презентации
* Климатизация
* WC
* Вендинг машина напитки, кафе, вафли
* Провеждане на демонстрации, хакер маратони
* Варианти за достъп: с чип карта, за всички членове или за основно
пребиваващите в лаба, които да отварят на членове без карта/ключ
* Заключващи се шкафчета за лични вещи, компютри
* Постоянни PC машини за общо ползване
* Вътрешен правилник
* Тераса
* Интернет

Определени бяха следните етапи в създаването на лаба:

Етап 1: покриване на минималното нужно за неговото функциониране

1. Помещение, минимално обзаведено
2. Интернет
3. Вътрешен правилник
4. Кът за трапезария

Етап 2: след заработване и установяване на лаба

1. Създаване на юридическо лице – Сдружение с нестопанска цел
2. Провеждане и огранизиране на платени курсове, презентации и събития за
допълнително финансиране на лаба

Членство и членски внос

Дефинирани бяха две възможни форми на членуване в лаба:

1. Общи членове на лаба: Достъп до лаба 24/7, свободно ползване на общата
база на лаба (т.н. hackerspace), възможност за достъп на външни лица с
придружител член.

2. Членове на лаба ползващи го като собствен офис: със собствено обособено
и запазено място (бюро) за работа. Могат евентуално да имат собствена една
или повече отделни стаи в лаба.

След гласуване с обикновено мнозинство бяха взети следните решения:

1. Лаб Пловдив да има както общ хакер-спейс (за всички членове) така и
обособено работно пространство за членове, които да го ползват като техен
постоянен офис (co-worker спейс).

2. Месечен членски внос от 25лв за общите членове на лаба.

3. Месечен членски внос от 100лв за членове на лаба, които ще го ползват като
офис и ще имат обособено място за работа там. Техни фирмени сътрудници ще
могат да ползват намаление, чиито размер не беше решен.

4. Месечен членски внос от 10 лв за ученици.

Извърши се преброяване изявилите желание да бъдат членове:

1. Като общи членове с 25 лв месечен членски внос: 30 човека
2. Като общи членове ученици с 10 лв месечен членски внос: 2 човека
3. Като фрийлансъри с 100 лв месечен членски внос за офис място: 5 човека

След преброяването беше съставен списък с имената и телефонните номера на
желаещите да бъдат членове.

Проведе се дискусия за управлението и общото събрание на лаба.

Бяха дефинирани следните екипи, след което за участие тях се записаха
доброволци:

* Екип за избор на място на лаба
* Екип за създаване на правилник
* Екип за създаване и поддръжка на сайт на лаба
* Екип за маркетинг
* Касиер, също за плащане на сметки
* Секретар, за водене на протоколи и документация
* Домакин(и) на лаба
* Екип за техническа поддръжка
* Екип за организиране на събития и курсове
* Екип за набиране на партньори и спонсори

Решено беше следващата среща да се проведе на същото място (Арт Кафе) на 22 май
от 18:30ч. На нея желаещите да бъдат членове да носят двойния размер на
месечния членски внос за заплащане на първоначалната такса. Ще се обсъдят
предложени места за лаба, правилник и ще бъдат гласувани отговорници за
екипите.

Срещата приключи в 21:30ч с бира :)

CORS Filter 1.6 supports any URI scheme

CORS FilterThe Java CORS Filter for adding Cross-Origin Resource Sharing to existing web apps received an important update to permit any URI scheme, not just the ubiquitous http:// and https:// as originally supported. This change is in line with RFC 6454 which defines the concept of web origins.

This means that now you can also service CORS requests for “custom” schemes as app://, fb:// , etc.

The new CORS Filter release should reach Maven Central later today. You can also get it from the CORS Filter Git repo at Bitbucket.

Cheers to Edraí Brosa for initiating this important change!

 

All JSON-RPC 2.0 libraries are now in Maven Central

masthead-jsonrpc2baseThe migration from Ant to Maven is now complete and all Java libraries for handling JSON-RPC 2.0 messages are now published in Maven Central.

You can find them under the com.thetransactioncompany.com groupId:

The useful JSON-RPC 2.0 Shell tool, available for purchase, has also been completely mavenised. It has found a lot of use in Android development recently and there have been plans to add HTTP basic authentication support to it (via a prompt).

JSON-RPC 2.0 libraries and tools switch to Maven

masthead-jsonrpc2baseThe Java libraries and tools for JSON-RPC 2.0 message serving and processing now use Apache Maven to build.

Migrating the previous Apache Ant scripts took about a day a to complete and was not without hassles, notable the ZIP package distribution and the automatic versioning of JavaDocs. We’ll now be able to gain from Maven’s automatic dependency resolution and I have gained enough knowledge to begin considering myself a Maven power user :)

The following related JSON-RPC 2.0 projects also got a Maven make-over:

Publishing to Maven Central is on the to-do list complete now :)

The JSON-RPC 2.0 Client can now handle GZIP and DEFLATE compression

Does your JSON-RPC server return large amounts of data? If so applying HTTP response compression can greatly reduce network traffic and response time, occasionally by a whole magnitude if your JSON structures contain long repeating keys or values.

Today we released a new version of the JSON-RPC 2.0 Client library for Java that adds support for GZIP and DEFLATE compression. These two algorithms are commonly implemented by web servers such as Apache HTTPD and Apache Tomcat.

To enable HTTP response compression in your Java client app:

URL serverURL = new URL("http://example.com/jsonrpc2/");

JSONRPC2Session mySession = new JSONRPC2Session(serverURL);

mySession.getOptions().enableCompression(true);

The JSON-RPC client will then set the Accept-Encoding request header to signal that it can process compressed responses. Note that many web servers don’t have HTTP compression enabled by default so this setting will simply be ignored by them.

To enable compression in Apache Tomcat you need to configure the HTTP connector by setting compression to “on”.

The JSON-RPC client will then automatically decompress the HTTP responses before processing the JSON payload.

The new version of the JSON-RPC client library also improves HTTP cookie support. It has dropped the primitive internal cookie store in favour of the standard java.net.CookieManager so now cookie expiration and replacement are also handled.

Opera finally with CORS support

Opera was the last major browser to add support for handling cross-origin requests in its 12th version. The CORS protocol was devised several years ago by a W3C working group to allow for clean making of cross-domain XHR, without JSONp hacks. CORS was initially adopted by Firefox and Chrome, and was subsequently joined by the other major players, such as Microsoft’s Internet Explorer.

Today more than 85% of the browsers on the web support CORS and an increasing number of developers are starting to use the protocol, judging by downloads of our CORS Filter package which allows CORS support to be easily retrofitted to any Java web app or service. When the new Opera 12 appeared the CORS Filter was successfully tested under it.

Thanks to Joost Cassee the CORS filter is now also available on Maven.

Access filters for JSON-RPC 2.0 services

Services on the web often have to be controlled for who and how accesses them. If they deal with sensitive data, such as usernames and passwords, you may want to ensure that all requests come in over encrypted HTTPS. If you’re running a private service, you may want to ensure that only selected internet hosts can make use of it. Or you may want to limit access to portions of the web API, such as administration, to selected users and clients.

For this purpose I created an Access Filter package for JSON-RPC 2.0 services. Today I released it to the public in its stable 1.1 version under a generous Apache 2.0 licence. I wanted filtering to be fast and robust, so the package was designed to be as simple and efficient as possible. It also nicely complements the proven Java libraries JSON-RPC 2.0 Base and JSON-RPC 2.0 Server.

The package defines four basic filters:

  • HostFilter Access filter ensuring JSON-RPC 2.0 requests originate from selected host names / IP addresses.
  • HTTPSFilter Access filter ensuring requests are passed over HTTPS.
  • X509ClientCertFilter Access filter ensuring HTTPS requests carry an X.509 client certificate with optional specified principal (subject DN).
  • APIKeyFilter Access filter ensuring clients present an API key for protected JSON-RPC 2.0 request methods.

There is a ready CompositeFitler which combines these four basic filters into a chain. You can then plug this filter chain into your JSON-RPC 2.0 service and call it prior to passing the incoming requests to the actual execution logic.

The CompositeFilter can be configured with a simple properties text file. The properties format is detailed in the JavaDocs for the CompositeFilterConfiguration class.

access.https.require=true
access.https.requireClientCert=true
access.https.clientCertPrincipal=cn=John Doe,ou=people,cd=company,dc=org
 
access.hosts.allow=*
 
access.apiKeys.require=true
access.apiKeys.exemptedMethods=ws.getName ws.getVersion ws.getTime
access.apiKeys.map.f70defbe-b881-41f8-8138-bea52b6e1b9c=sso.login sso.logout sso.getSession
access.apiKeys.map.08d1e641-b1c1-4d88-8796-e47c06430efb=sso.proxiedLogin sso.proxiedLogout sso.getSession
access.apiKeys.map.d881afe0-4d7d-4520-9fda-bffffc3022ba=sso.userCount sso.sessionCount sso.listUsers

Alternatively, you may devise your own custom filter chain, based on the AccessFilterChain class.

How do you use the CompositeFitler?

// Parse config from properties, create composite filter
java.util.Properties props = ...
CompositeFilter filter = new CompositeFilter();
filter.init(new CompositeFilterConfiguration(props)); 

// Invoke the filter for each incoming JSON-RPC 2.0 request

// Parse JSON-RPC 2.0 request
JSONRPC2Request request = JSONRPC2Request.parse(...);

// Set the message context, i.e. client host IP, etc.
MessageContext mctx = new MessageContext(...);

// Call the filter
AccessFilterResult result = filter.filter(request, mctx);

if (result.accessAllowed()) {
    // Continue with request processing...

}
else {
    // Return specified access denied JSON-RPC 2.0 error
    // to the calling client
    JSONRPC2Error error = result.getAccessDeniedError().toJSONRPC2Error();
}

The Access Filter package is available at Bitbucket: https://bitbucket.org/vdzhuvinov/access-filter/

We plan to integrate into the upcoming new releases of the Json2Ldap, NimbusSSO and AuthService web services from NimbusDS software.

If you have comments of feedback to share, get in touch or leave a ticket at the Bitbucket repo.

New public repos

The open source projects led by Dzhuvinov Software can now be followed through their new public Git repos at Bitbucket.

For an overview of the Git repos go to https://bitbucket.org/vdzhuvinov.

CORS Filter

CORS Filter is the first universal solution for fitting Cross-Origin Resource Sharing (CORS) support to Java web applications. CORS is a recent W3C effort to introduce a standard mechanism for enabling cross-domain requests in web browsers and participating servers.

Its Git repo is at https://bitbucket.org/vdzhuvinov/cors-filter

JSON-RPC 2.0 Base

Minimalist Java library for composing and parsing JSON-RPC 2.0 messages. No framework or transport layer dependencies. Batching left out for simplicity.

Its Git repo is at https://bitbucket.org/vdzhuvinov/json-rpc-2.0-base

JSON-RPC 2.0 Client

Minimal Java client-side library for dispatching requests and notifications to a JSON-RPC 2.0 server by means of HTTP(S) POST.

Its Git repo is at https://bitbucket.org/vdzhuvinov/json-rpc-2.0-client

JSON-RPC 2.0 Server

Simple server framework for processing JSON-RPC 2.0 requests and notifications.

Its Git repo is at https://bitbucket.org/vdzhuvinov/json-rpc-2.0-server

Pretty JSON

Pretty JSON formatter for Java.

Its Git repo is at https://bitbucket.org/vdzhuvinov/pretty-json

Java Property Utils

Typed retrieval of java.util.Properties as boolean, integer, floating point, string and enum values.

Its Git repo is at https://bitbucket.org/vdzhuvinov/java-property-utils