简体   繁体   中英

Azure Chatbot Token Server

I have an azure chat bot and I use it per direct line channel. It is working fine if I use the secret directly in the HTML, but due to safety reasons I want to use Tokens. Thats why I used that:

<script>

    window
        .fetch('http://XXXXXXXX.azurewebsites.net/token-generate', 
        { 
            method: 'POST'
        })
        .then(function(res) {
          return res.json();
        })
        .then(function(json) {
          const token = json.token;

        window.WebChat.renderWebChat({
                directLine: window.WebChat.createDirectLine({
                  token: token
                })
              }, 
              document.getElementById('webchat'));
              document.querySelector('#webchat > *').focus();
            });

    </script>

It is like that and not with an async function because it needs to work on IE11 too.

My index.js in my bot looks like this:

// Create HTTP server
const server = restify.createServer({
  name: 'token-server'
});
server.listen(process.env.port || process.env.PORT || 3978, function() {
    console.log(`\n${ server.name } listening to ${ server.url }`);
    console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
    console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});

server.post('/token-generate', async (_, res) => {
  console.log('requesting token ');
  res.setHeader('Access-Control-Allow-Origin', '*');
  console.log(res);

  try {
    const cres = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
      headers: { 
        authorization: `Bearer ${ process.env.DIRECT_LINE_SECRET }`
      },
      method: 'POST'
    });
 //   console.log(cres);
    const json = await cres.json();
 //   console.log(json);
   // json.header.append('Access-Control-Allow-Origin: *');
    console.log(json);

    if ('error' in json) {
      res.send(500);
    } else {
      res.send(json);
    }
  } catch (err) {
    res.send(500);
  }
});

That is some code I found after some research how to use tokens to render the Webchat.

My problem is, that when I use this html code, I get some Errors:

Access to fetch at 'http://compliancebotbbraun-bot.azurewebsites.net/token-generate' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
testbot.html:1 Uncaught (in promise) TypeError: Failed to fetch

and I just don't know how to change the Access-Control-Allow-Origin header. I don't find anything online and if I find something, it is not even close to my code. It is working exactly as I tought it would work in IE11, but in Chrome,Edge and Firefox (idk for others, only tested these) these Errors are occuring.

I hope someone here can help me.

Based on my understanding , you exposed an API to grant access tokens to your bot clients by post method to your bot clients. Your bot clients use JS script to invoke this API . As you are using post method, so your bot clients will encounter CORS issues .

Based on the host of /token-generate url , this API is hosted on Azure webapp , you can just refer to this doc to define allowed domains to call this API from a static page by JS on Azure portal directly.

You can find the Azure webapp which hostes your API code here : 在此处输入图片说明

And open CORS settings here : 在此处输入图片说明

If you are just testing your bot from local static html file , adding "*" and remove other domains in CORS config will solve this issue . 在此处输入图片说明

Test result : 在此处输入图片说明

Hope it helps . If you have any further concerns , pls feel free to let me know .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM