Cask (undertow) 服务器配置,用于使用 CORS 进行不记名令牌身份验证

问题描述 投票:0回答:1

我已经为 CORS 配置了 Cask undertow 服务器,如下所示:

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)
    }
}

我想向服务器发出 CORS 请求,并传入不记名令牌 这是我针对该请求的客户端代码

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

请注意,我为请求生成了以下标头

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;
    }

当我提出该请求时,我在飞行前检查期间从服务器收到 405“方法不允许”错误。 但是,从 Postman/curl 调用相同的方法可以正常工作。此外,如果我从请求中删除 Authorization 标头,它也会返回响应。我不太确定还应该做什么来正确配置此请求。 有什么建议吗?

typescript scala cors bearer-token undertow
1个回答
0
投票

供将来参考,这对我不起作用的原因是我没有在服务器端正确处理

OPTIONS
动词。 服务器应通过返回
200
204
状态代码来应答 OPTIONS 请求(请参阅 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)。

© www.soinside.com 2019 - 2024. All rights reserved.