Проблемы с аутентификацией на нод-мыле - PullRequest
0 голосов
/ 07 октября 2018

Спасибо, что нашли время, чтобы прочитать это,

У меня небольшая проблема с мылом-узлом, поэтому в основном я пытаюсь проверить личность клиента перед отправкой ответа, послеВ документации я нашел функцию server.authenticate.

server.authenticate = async function (security: any) {
                const binarySecurityTokenAsBase64String = security.BinarySecurityToken.$value;
                const pemKeyFromRequestAsString = "-----BEGIN CERTIFICATE-----" + "\n" + binarySecurityTokenAsBase64String.replace(/(.{64})/g, "$1\n") + "\n" + "-----END CERTIFICATE-----";
                const success =  await validateCertificate(pemKeyFromRequestAsString);
                if (success) {
                    return true;
                } else {
                    winston.warn("Failed to validate Certificate - Either Certificate Verification with CA Chain Failed or the system encountered an error");
                    return false;
                }
            };

Вот где я занимаюсь проверкой и возвращаю значение true или false на основании результата:

const success =  await validateCertificate(pemKeyFromRequestAsString);

Моя проблема в том, что независимо от результата, я все равно получаюОтветьте, в журналах все в порядке и подтвердите, что проверка не удалась, может быть, это из-за асинхронного / синхронизирующего материала. Я действительно новичок в мире Javascript / Typescript, любая помощь будет принята с благодарностью.

Вот мой предварительный просмотр моего кода:

try {
        const myService = {
            Calculate_Service: {
                Calculate_Port: {
                    multiply: function(args, callback) {
                        const a = 1;
                        try {
                            winston.debug("Reached the multiply Function");
                            const n = args.a * args.b;
                            callback({
                                multiplicationResult : n
                            });
                        } catch (e) {
                            winston.error(e);
                            throw {
                                Fault: {
                                    Code: {
                                        Value: "soap:Sender",
                                        Subcode: { value: "rpc:BadArguments" }
                                    },
                                    Reason: { Text: JSON.stringify(e) },
                                    statusCode: 500
                                }
                            };
                        }

                    },
                }
            }
        }

        const xml = fs.readFileSync(AppConfiguration.responseServerWsdlPath, "utf8");

        app.use(bodyParser.raw({
            type: function () {
                return true;
            }, limit: "5mb"
        }));

        app.listen(port, async function () {

            winston.info("Express server listening on port " + port);
            const server = ArcNodeSoap.listen(app, "/calculatorService", myService, xml);

            server.authenticate = async function (security: any) {
                const binarySecurityTokenAsBase64String = security.BinarySecurityToken.$value;
                const pemKeyFromRequestAsString = "-----BEGIN CERTIFICATE-----" + "\n" + binarySecurityTokenAsBase64String.replace(/(.{64})/g, "$1\n") + "\n" + "-----END CERTIFICATE-----";
                const success =  await validateCertificate(pemKeyFromRequestAsString);
                if (success) {
                    return true;
                } else {
                    winston.warn("Failed to validate Certificate - Either Certificate Verification with CA Chain Failed or the system encountered an error");
                    return false;
                }
            };

            server.log = function (type, data) {
                winston.debug("type: " + type);
                winston.debug(JSON.stringify(data));
            };

                server.on("headers", function (headers, methodName) {
                    //More debug stuff;
                    winston.debug("****** HEADERS **********");
                    winston.debug(JSON.stringify(headers));
                    winston.debug("methodName: " + methodName);
                    winston.debug("*************************")

                });
        });
    } catch (err) {
        winston.error(err);
    }

Я ценю время, ребята, спасибо!

1 Ответ

0 голосов
/ 08 октября 2018

Я наконец-то исправил свою проблему, если у кого-то возникла такая же проблема с кодом асинхронизации / синхронизации: я исправил ее с помощью метода Async из документации

server.authenticate =  function (security: any, callback): any {
                //Get the Binary Security Token coming from the request as a Base 64 String
            const binarySecurityTokenAsBase64String = security.BinarySecurityToken.$value;
            //Creating a new certificate with header, footer and line breaks from the binarySecurityTokenAsBase64String
            const pemKeyFromRequestAsString = "-----BEGIN CERTIFICATE-----" + "\n" + binarySecurityTokenAsBase64String.replace(/(.{64})/g, "$1\n") + "\n" + "-----END CERTIFICATE-----";
            //Validate the certificate

                //This is an async wrapper where I added all my verification steps;
                validateCertificateWrapper(pemKeyFromRequestAsString).then((authorized: boolean) => {
                    //If the certificate is valid
                    if (authorized) {
                        winston.info("Verification successfully Passed");
                        return callback(true);

                    } else {                     //If the certificate is invalid
                        winston.error("Failed to validate Certificate");
                        return callback(false);
                    }
                }, () => {
                    winston.error("Failed to validate Certificate");
                    return callback(false);
                } );
            };
...