Cask (undertow) server configuration for bearer token auth with CORS

70 Views Asked by At

I have configuration my Cask undertow server for CORS like so:

class CorsHandler(dispatchTrie: DispatchTrie[Map[String, (Routes, EndpointMetadata[_])]],
                  mainDecorators: Seq[Decorator[_, _, _]],
                  debugMode: Boolean,
                  handleNotFound: () => Response.Raw,         
                  handleMethodNotAllowed: () => Response.Raw,         
                  handleError: (Routes, EndpointMetadata[_], Result.Error) => Response.Raw)
extends Main.DefaultHandler(dispatchTrie, mainDecorators, debugMode, handleNotFound, handleMethodNotAllowed, handleError)(CorsHandler.log) {
    import CorsHandler._
    override def handleRequest(exchange: HttpServerExchange): Unit = {        
        exchange.getResponseHeaders
        .put(accessControlAllowOrigin, "http://localhost:3000")
        .put(accessControlAllowCredentials, accepted)
        .put(accessControlAllowMethods, "POST,GET,PUT,DELETE,PATCH,HEAD,OPTIONS")
        .put(acccessControlAllowHeaders, "Origin,Accept,Authorization,Content-Type,X-Requested-With")     
        // .putAll(acccessControlAllowHeaders, headers)
        // .putAll(accessControlAllowMethods, methods)
        super.handleRequest(exchange)
    }
}

And I would like to make a CORS request to the server, passing in a bearer token This is my client code for that request

const headers = this.appendTokenToHeader(token);
        return fetch(url, 
            {
                method: 'GET',                
                mode: 'cors',
                credentials: 'include',
                headers: headers
            })
        .then(res => res.json())
        .catch(console.error);

Note that I generate the following headers for the request

appendTokenToHeader = (token: string): Headers => {
        const headers = new Headers();
        headers.append('Accept', '*/*');
        headers.append('Accept-Encoding', 'gzip, deflate, br');
        headers.append('Accept-Language', 'en-US,en;q=0.9');
        headers.append('Connection', 'keep-alive');        
        headers.append('Authorization', `Bearer ${token}`);
        return headers;
    }

When I make that request I get a 405 "Method not allowed" error from the server during pre-flight checks. However, calling this same method from Postman/curl works correctly. Moreover, if I remove the Authorization header from the request, it will also return a response. I'm not really sure what else I should do to configure this request correctly. Any suggestions?

1

There are 1 best solutions below

0
Locust5304 On

For future reference, the reason this wasn't working for me was that I wasn't handling the OPTIONS verb correctly on the server side. The server should answer the OPTIONS request by returning either a 200 or a 204 status code (see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).