Why do I get an Azure key Vault No-cors policy error?

153 Views Asked by At

I get this error:

localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

import React, { useState, useEffect } from 'react';
import axios from 'axios'
import { SecretClient } from '@azure/keyvault-secrets';
import { useMsal, useIsAuthenticated } from '@azure/msal-react'

const App = () => {
    const { instance } = useMsal()
    const [secretValue, setSecretValue] = useState('');


useEffect(() => {

    const CurrentAccount = instance.getActiveAccount()
        const request = {
            scopes: ['openid', 'profile', 'user.read', 'user.read.all'],
            account: CurrentAccount
        }
        const response = await instance.acquireTokenSilent(request)
        console.log(response.accesstoken)//to get accesstoken code with single sign on.

      const getSecret = async () => {
            const vaultName = '<YOUR_KEY_VAULT_NAME>';
            const url = `https://${vaultName}.vault.azure.net/secrets/<YOUR_SECRET_NAME>?api-     version=7.0`;
            const headers = {
                 Authorization: `Bearer ${response.accesstoken}`
            };

      try {
        const response1 = await axios.get(url, { headers });
        setSecretValue(response1.data.value);
      } catch (error) {
        console.error('Error retrieving secret:', error);
      }
    };

    getSecret();
  }, []);

  return (
    <div>
      <p>Secret value: {secretValue}</p>
    </div>
  );
};

export default App;

1

There are 1 best solutions below

0
On

When making requests to Azure Key Vault, we need to check that the server or Azure Function allows requests from the domain where the React application is hosted.

  • Set the appropriate CORS headers in the response. You can do this by adding the Access-Control-Allow-Origin header.
module.exports = async function (context, req) {
    context.res = {
        status: 200,
        headers: {
            'Access-Control-Allow-Origin': '<Your React App Origin>',
            'Access-Control-Allow-Methods': 'GET, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization'
        },
        body: /* Your response body here */
    };
};

In portal:

enter image description here

  • I noticed an issue with the code you provided. It seems there's an indentation problem please check once again, and the await keyword is used outside an asynchronous function.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useMsal } from '@azure/msal-react';  // Remove SecretClient import

import logo from './logo.svg';
import './App.css';

function App() {
  const { instance } = useMsal();
  const [secretValue, setSecretValue] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      try {
        const currentAccount = instance.getActiveAccount();
        const request = {
          scopes: ['openid', 'profile', 'user.read', 'user.read.all'],
          account: currentAccount,
        };
        const response = await instance.acquireTokenSilent(request);

        const vaultName = ' ';
        const secretName = ' ';
        const url = `https://${vaultName}.vault.azure.net/secrets/${secretName}?api-version=7.0`;

        const headers = {
          Authorization: `Bearer ${response.accessToken}`,
        };

        const response1 = await axios.get(url, { headers });
        setSecretValue(response1.data.value);
      } catch (error) {
        console.error('Error retrieving secret:', error);
      }
    };

    fetchData();
  }, [instance]);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Secret value: <strong>{secretValue}</strong>
        </p>
        <p>
          Learn <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            React
          </a>
        </p>
      </header>
    </div>
  );
}

export default App;

Result:

enter image description here

enter image description here