NeilMadden/apisecurityinaction

CORS error

Opened this issue · 0 comments

I've completed all the first section of chapter 5.

I've created a CorsFilter class with this content

package com.manning.apisecurityinaction;

import spark.Filter;
import spark.Request;
import spark.Response;

import java.util.Set;

import static spark.Spark.halt;

public class CorsFilter implements Filter {

    private final Set<String> allowedOrigins;

    public CorsFilter(final Set<String> allowedOrigins) {
        this.allowedOrigins = allowedOrigins;
    }

    @Override
    public void handle(final Request request, final Response response) throws Exception {
        var origin = request.headers("Origin");
        if (origin != null && allowedOrigins.contains(origin)) {
            response.header("Access-Control-Allow-Origin", origin);
            response.header("Access-Control-Allow-Credentials", "true");
            response.header("Vary", "Origin");
        }

        if (isPreflightRequest(request)) {
            if (origin == null || !allowedOrigins.contains(origin)) {
                halt(403);
            }

            response.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-CSRF-Token");
            response.header("Access-Control-Allow-Methods", "GET, POST, DELETE");
            halt(204);
        }
    }

    private boolean isPreflightRequest(final Request request) {
        return "OPTIONS".equals(request.requestMethod())
                && request.headers().contains("Access-Control-Request-Method");
    }
}

In the Main class I added this line before(new CorsFilter(Set.of("https://localhost:9999"))); after the ReteLimiter. And in the login.js file I edited the fetch

fetch('https://localhost:4567/sessions', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': credentials
        }
    }).then(response => {
        if (response.ok) {
            response.json()
                .then(json => {
                    document.cookie = `csrfToken=${json.token};Secure;SameSite=strict`
                })
            window.location.replace('/natter.html');
        }
    }).catch(error => console.error(`Error: ${error}`));

I run the application on port 4567 and 9999.
Through postman I created the user with this curl

curl --location --request POST 'https://localhost:4567/users' \
--header 'Content-Type: application/json' \
--data-raw '{
    "username": "Dennis",
    "password": "changeit"
}'

then I open login.html at the addredd https://localhost:9999/login.html and I tried to login using Dennis as username and changeit as password but I still receive CORS errors. What I'm doing wrong?

Here my code https://github.com/DennisBoanini/apisecurityinaction on branch feature/chapter-5

Thank you all!