Yan Ivan Evdokimov
Yan Ivan Evdokimov

Reputation: 179

CORS filter not working with Java + angularjs

I am using Java as back-end (RESTful services) and Angularjs as front-end. The problem is that back-end and front-end applications are on different ports, so I need to use CORS filter. It looks like this:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CORSFilter implements Filter {

    public CORSFilter() {
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(
        ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

        ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) response).addHeader("Access-Control-Allow-Methods", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
        ((HttpServletResponse) response).addHeader("Access-Control-Allow-Headers", "GET, PUT, OPTIONS, X-XSRF-TOKEN");

        chain.doFilter(request, response);
    }
}

web.xml:

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.company.companyserver.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

RESTful services:

@POST
@Path("login")
@Produces("application/json")
public Response login(@Context HttpServletRequest req, UserTable user) {
    req.getSession(true);
    if (req.getUserPrincipal() == null) {
        try {
            req.login(user.getUsername(), user.getPassword());
        } catch (ServletException e) {
            return Response.status(Response.Status.BAD_REQUEST).type("text/plain").entity("Login or Password is incorrect").build();
        }
    } else {
        return Response.status(Response.Status.OK).type("text/plain").entity("You are already logged in").build();
    }
    return Response.status(Response.Status.OK).type("text/plain").entity("Login successfull").build();
}

@GET
@Path("logout")
@Produces("application/json")
public Response logout(@Context HttpServletRequest req) {
    try {
        req.logout();
        req.getSession().invalidate();
    } catch (ServletException e) {
        return Response.status(Response.Status.BAD_REQUEST).type("text/plain").entity("Can not logout").build();
    }
    return Response.status(Response.Status.OK).type("text/plain").entity("Logout successfull").build();
}

Front-end:

 $http.post(apiUrl + 'usertable/login', {
        username: 'admin',
        password: 'admin'
    });

    $http.get(apiUrl + 'usertable/logout').success(function (a) {
        var o = a;
    });

Every time I check getUserPrincipal() in my RESTful services, I get it to equal null. When my java and angularjs are deployed on the same server and port - everything works fine. How to make it working on different ports?

Upvotes: 1

Views: 1107

Answers (2)

Mihai Bucurica
Mihai Bucurica

Reputation: 11

First of all you have an error here:

((HttpServletResponse) response).addHeader("Access-Control-Allow-Methods", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
((HttpServletResponse) response).addHeader("Access-Control-Allow-Headers", "GET, PUT, OPTIONS, X-XSRF-TOKEN");

The headers are "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With" and the methods "GET, PUT, OPTIONS, X-XSRF-TOKEN".

Try this first.

Upvotes: 1

Yadu Krishnan
Yadu Krishnan

Reputation: 3522

I have used CORS in one of my previous java projects. There I was using the org.apache.catalina.filters.CorsFilter and it was working fine.

Try, if the below code is working.

    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
        <init-param>
            <param-name>cors.allowed.origins</param-name>
            <param-value>*</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.methods</param-name>
            <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.headers</param-name>
            <param-value>Content-Type,X-Requested-With,Accept,Accept-Encoding,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Upvotes: 1

Related Questions