2
votes

I have java spark api configured for basic api. When i call URL(with basic auth) from Postman, it returns JSON. But when i call same URL from Angular 4 application it returns: Response for preflight has invalid HTTP status code 401. Headers in angular are properly set and i already read this answer: Angular 2 - Response for preflight has invalid HTTP status code 401

And i know problem is in API, but i don't know how to configure it to allow OPTIONS from browser before auth. Code of route creation is in code below

    private static void create_routes() {

    staticFileLocation("/static");

    Spark.options("/*", (request, response) -> {

        String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
        if (accessControlRequestHeaders != null) {
            response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
        }
        String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
        if (accessControlRequestMethod != null) {
            response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
        }
        return "OK";
    });

    Spark.before((request, response) -> {
        response.header("Access-Control-Allow-Origin", "*");
    });

    RouteOverview.enableRouteOverview("/debug"); 
    path("/api", () -> {
        before("/*", new SecurityFilter(authConfig, "DirectBasicAuthClient"));
    });
    after("/api/*", (request, response) -> response.type("application/json"));

    new ApiController();
}
1

1 Answers

0
votes

You have to add OPTION as request method:

Spark.before((request, response) -> {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Request-Method", "GET,POST,PUT,DELETE,OPTIONS");
});