Shaik Moulali
Shaik Moulali

Reputation: 61

How to use Azure Key Vault secrets in react App?

I tried to read the Azure Key Vault in React App using DefaultAzureCredentials, but is not working.

Tried every other way but no luck.I heard we cannot read KV Secrets in Client Side. Can anyone help on how to read this secrets.

I tried to Get the secrets from KV using

Upvotes: 1

Views: 1145

Answers (1)

Dasari Kamali
Dasari Kamali

Reputation: 3649

I tried the frontend with React JS and backend with JavaScript to retrieve Azure Key Vault secret using DefaultCredentials.

Code :

backend/server.js :

const express = require('express');
const axios = require('axios');
const { DefaultAzureCredential } = require('@azure/identity');
const { SecretClient } = require('@azure/keyvault-secrets');
const cors = require('cors');
const app = express();

const vaultUrl = 'https://<keyvault_name>.vault.azure.net';
const secretName = '<secret_name>';

app.use(express.json());
app.use(cors()); 
app.get('/api/secret', async (req, res) => {
  try {
    const credential = new DefaultAzureCredential();
    const client = new SecretClient(vaultUrl, credential);
    const secret = await client.getSecret(secretName);

    res.json({ value: secret.value });
  } catch (error) {
    console.error('Error retrieving secret:', error);
    res.status(500).send('Error retrieving secret');
  }
});

const port = process.env.PORT || 3000; 
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

package.json :

"dependencies": {
        "@azure/identity": "^4.0.1",
        "@azure/keyvault-secrets": "^4.8.0",
        "axios": "^0.24.0",
        "cors": "^2.8.5",
        "express": "^4.17.2"
    }

frontend :

src/components/SecretReader.js :

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const SecretReader = () => {
  const [secretValue, setSecretValue] = useState(null);

  useEffect(() => {
    const getSecret = async () => {
      try {
        const response = await axios.get('http://localhost:3000/api/secret');
        setSecretValue(response.data.value);
      } catch (error) {
        console.error('Failed to retrieve secret:', error.message);
      }
    };

    getSecret();
  }, []);

  return (
    <div>
      <h2>Secret Value</h2>
      <p>{secretValue}</p>
    </div>
  );
};
export default SecretReader;

src/App.js :

import React from 'react';
import SecretReader from './components/SecretReader';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>My Azure Key Vault Secret Reader</h1>
      </header>
      <main>
        <SecretReader />
      </main>
    </div>
  );
}
export default App;

I provided access to my app, allowing it to retrieve the secret from the Azure Key Vault, as shown below:

enter image description here

Output :

The backend code started running on port 3000 as shown below.

enter image description here

I retrieved the secret from the Azure Key Vault as shown below.

http://localhost:3000/api/secret
{
    "value": "Hi Kamali"
}

enter image description here

Then, I started my frontend React.js code on port 3001 as shown below.

enter image description here

I successfully retrieved the secret from the Azure Key Vault as shown below.

http://localhost:3001/
My Azure Key Vault Secret Reader
Secret Value
Hi Kamali

enter image description here

Upvotes: 3

Related Questions