1
votes

I'm trying to implement cors on Jersey using Tomcat with basic authentication. The Authentication is configured using a realm, that get the data of the database and compare with the given user and pass.

All my resources are working normally without cross-origin HTTP request, i've tested using Soapui and a Android application made by myself. The problem occours when i try to consume the REST webservice using jQuery and ajax, that sends a Options preflight without any authentication data, and the server responds with a 401 unauthorized error.

I've tried to do the follow:

*Implement a custom container filter to treat that cors request, and nothing. Use the catalina cors filter as suggested by the site http://enable-cors.org, And nothing.

*Use the cors filter developed by: http://software.dzhuvinov.com/cors-filter.html. Nothing.

*Use the filter of the servlet specification, with and without the WebFilter annotation, and nothing.

*Create the options service with the @PermitAll annotation.

In all this attempts, i have configured the web.xml too. I'm using Tomcat 7.0.21, Jersey 2.22.2, Hibernate, MYSQL, JDK 7 and Maven.

I think that the basic auth is the problem, maybe i should try the OAuth 2.0? Is there a way to make cors works with the Basic Auth? How to Proceed?

1
Isn't, because i have tried these solutions before and like i said, no effect. The server still requesting basic auth for the options method, so, even that i send the access authorization header and implement the filters, the server still responding a 401 error because no authorization data was sended from ajax clientMihael Zamin

1 Answers

0
votes

The easiest way that worked for me was to do the following:

1) Add this code to your web.xml near the top just inside of the <web-app .. > tag

 <filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

2) Import two libraries via maven in pom.xml

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>java-property-utils</artifactId>
    <version>1.9.1</version>
</dependency>

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>1.9.1</version>
</dependency>

Good luck!