Search code examples
azure-cognitive-services

How to fetch credential for azure cognitive speech services


I have created a Speech Cognitive services on Azure portal and I would like to follow this guideline. somewhere in the mentioned guideline there is something like the following:

fetch('https://webchat-mockbot.azurewebsites.net/speechservices/token', { method: 'POST' }).

My question is with which address should I replace this part of the code? I have tried several things with no success. For instance, I tried https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken and tried to give one of the two keys that I see under Keys and Endpoints as the parameter of the post method. But it didn't work. I even tried using subscription key and the region, but it also didn't work. Maybe I have not used the correct syntax.

I would be grateful if anybody could help me.

Update: Here is my updated code which still has problem with the microphone:

    <!DOCTYPE html>
    <html lang="en-US">

    <head>
<title>Web Chat: Cognitive Services Speech Services using JavaScript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
        html,
        body {
            height: 100%;
        }

        body {
            margin: 0;
        }

        #webchat {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="webchat" role="main"></div>
    <script>
        function createFetchSpeechServicesCredentials() {
            let expireAfter = 0;
            let lastPromise;

            return () => {
                const now = Date.now();

                if (now > expireAfter) {
                    expireAfter = now + 300000;
                    lastPromise =  fetch(
                        'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken',
                        { method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'my_subscription-key-speech-services' } }
                    ).then(
                        res => res.json(),
                        err => {
                            expireAfter = 0;

                            return Promise.reject(err);
                        }
                    );
                }

                return lastPromise;
            };
        }

        const fetchSpeechServicesCredentials = createFetchSpeechServicesCredentials();

        (async function () {

            const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate',
                { method: 'POST', headers: { Authorization: 'Bearer My_direct_line_secret_key1' } });
            const { token } = await res.json();

            const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
                credentials: fetchSpeechServicesCredentials
            });

            window.WebChat.renderWebChat(
                {
                    directLine: window.WebChat.createDirectLine({ token }),
                    webSpeechPonyfillFactory
                },
                document.getElementById('webchat')
            );

            document.querySelector('#webchat > *').focus();
        })().catch(err => console.error(err));
    </script>
</body>
</html>

For simplicity, I copy the code which worked after the long discussion with @Hury Shen:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Web Chat: Cognitive Services Speech Services using JavaScript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
        html,
        body {
            height: 100%;
        }

        body {
            margin: 0;
        }

        #webchat {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="webchat" role="main"></div>
    <script>


       

        (async function () {

            const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST', headers: { Authorization: 'Bearer my-directline-secret-key' } });
            const { token } = await res.json();

            let authorizationToken;
            const tokenRes = await fetch(
                'https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken',
                { method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'my-cognitive-services-subscription-key' } }
            );

            if (tokenRes.status === 200) {
                region = 'westeurope', 
                authorizationToken = await tokenRes.text()
            } else {
                return (new Error('error!'))
            }

            const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
                authorizationToken: authorizationToken,
                region: region 
            });

            window.WebChat.renderWebChat({
                directLine: window.WebChat.createDirectLine({ token }),
                webSpeechPonyfillFactory: webSpeechPonyfillFactory
            }, document.getElementById('webchat'));
        })().catch(err => console.error(err));
    </script>
</body>
</html>

Best, Hanna


Solution

  • You need to use one of the keys under "Keys and Endpoints" in the header of your post request but not as the parameter of your post request. Below is a request sample for your reference:

    const tokenRes = await fetch(
      'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken',
      { method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'yourCognitiveServicesSubscriptionKey' } }
    );
    
    if (tokenRes.status === 200) {
      region = 'westus',
      authorizationToken = await tokenRes.text()
    } else {
      return (new Error('error!'))
    }
    

    You can also test it in postman. Below screenshot is my test, I put the key in "header" of the post request but not in "Params". enter image description here

    ======================Update=====================

    According to some test, I think you should use the endpoint address as below:

    If do it in one app service, you should use:

    https://webchat-mockbot.azurewebsites.net/directline/token

    The js code should be:

    const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });
    const { token } = await res.json();
    

    If just for test(expose the key in page), you should use:

    https://directline.botframework.com/v3/directline/tokens/generate

    The js code should be:

    const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST', headers: { Authorization: 'Bearer your_secret' }});
    const { token } = await res.json();
    

    ======================Update 2=====================

    You can modify your code according to the code below:

    let authorizationToken;
    const tokenRes = await fetch(
      'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken',
      { method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'yourCognitiveServicesSubscriptionKey' } }
    );
    
    if (tokenRes.status === 200) {
      authorizationToken = await tokenRes.text()
    } else {
      return (new Error('error!'))
    }
    
    const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory( {
      authorizationToken: authorizationToken
    } );
    
    window.WebChat.renderWebChat({
      directLine: directLine,
      webSpeechPonyfillFactory: webSpeechPonyfillFactory
    }, document.getElementById('webchat') );