Microsoft Fabric Updates Blog

Adding more flexibility to your business applications with support for Service Principal Names (SPNs) in Fabric API for GraphQL

 

We are enhancing enterprise-grade security and authentication by introducing Service Principal Names (SPN) support for API for GraphQL in Microsoft Fabric. This new feature offers organizations looking to integrate their apps with API for GraphQL in Microsoft Fabric tie seamlessly with their enterprise identity and access management systems. 

By leveraging SPNs, businesses can now implement robust application-to-GraphQL authentication without relying on user credentials. This facilitates automated processes and streamlines the management of complex applications and microservices architectures. It’s a perfect fit for the zero-trust security model, enabling the fine-grained access controls and auditing capabilities that are essential in today’s regulatory landscape. 

From a security standpoint, the benefits are clear. SPNs provide a secure method to authenticate service accounts, effectively reducing the risks associated with shared user accounts. This feature empowers administrators to apply the principle of least privilege, assigning only necessary permissions to each service principal. Moreover, it enhances auditing and monitoring capabilities, offering valuable insights into data access patterns and improving overall security posture. 

Getting started

Using SPNs with API for GraphQL is extremely simple: enable the use of Service Principals in your Fabric tenant then create an App Registration in Entra with a client secret. After that simply grant the App access to your GraphQL item in Fabric and data sources exposed by the API, and you’re all set. 

A screenshot of a computer

Description automatically generated  

A screenshot of a computer

Description automatically generated  

More specifically:

  1. Create a new Microsoft Entra app. In the new app, add a client secret under Certificates and Secrets, for more information see Register a Microsoft Entra app and create a service principal.
  2. In the Tenant Admin portal, go to Tenant Settings. Under Developer Settings enable Service Principals can use Fabric APIs. With this setting enabled, the application will be visible in the Fabric Portal for role or permissions assignment. You can find more information on Identity support.
  3. The service principal will need access to both the GraphQL API and the data source. In the Fabric Portal, add the application as a workspace member with a contributor role where both the GraphQL API and data source items are located.

Since a Service Principal requires either a certificate or a client secret, it is not supported by the Microsoft Authentication Library (MSAL) in single page applications (SPAs) like React apps. You can leverage a backend service properly secured with well-defined authorization logic depending on your requirements and use cases.

Once your API is configured to be accessed by a Service Principal, you can test it locally using a simple Node.JS application in your local machine:

const { ClientSecretCredential } = require('@azure/identity');

// Define your Microsoft Entra credentials
const tenantId = "<YOUR_TENANT_ID>";
const clientId = "<YOUR_CLIENT_ID>";
const clientSecret = "<YOUR_CLIENT_SECRET>"; // Service principal secret value

const scope = "https://api.fabric.microsoft.com/.default"; // The scope of the token to access Fabric

// Create a credential object with service principal details
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

// Function to retrieve the token
async function getToken() {
    try {
        // Get the token for the specified scope
        const tokenResponse = await credential.getToken(scope);
        console.log("Access Token:", tokenResponse.token);
    } catch (err) {
        console.error("Error retrieving token:", err.message);
    }
}

After installing the dependencies (@azure/identity) with your Node.JS package manager of choice, modifying the file with the required information, saving and executing it (node <filename.js>), you’ll be able retrieve a token from Entra.

The token can then be used to invoke your GraphQL API using PowerShell by replacing the appropriate details with the token you just retrieved, the GraphQL query you want to execute, and the GraphQL API Endpoint:

$headers = @{
    Authorization = "Bearer <YOUR_TOKEN>"
    'Content-Type' = 'application/json'
}

$body = @{
    query = @"
    <YOUR_GRAPHQL_QUERY>
"@
}

# Make the POST request to the GraphQL API
$response = Invoke-RestMethod -Uri "<YOUR_GRAPHQL_API_ENDPOINT>" -Method POST -Headers $headers -Body ($body | ConvertTo-Json)

# Output the response
$response | ConvertTo-Json -Depth 10 

Alternatively, you can use cURL to achieve the same result:

curl -X POST <YOUR_GRAPHQL_API_ENDPOINT> \
-H "Authorization: <YOUR_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"query": "<YOUR_GRAPHQL_QUERY(in a single line)>"}'

For local testing purposes, the Node.JS code can be slightly modified with an additional dependency (axios) to retrieve the token and invoke the API in a single execution:

const { ClientSecretCredential } = require('@azure/identity');
const axios = require('axios');

// Microsoft Entra credentials
const tenantId = "<YOUR_TENANT_ID>";
const clientId = "<YOUR_CLIENT_ID>";
const clientSecret = "<YOUR_CLIENT_SECRET>"; // Service principal secret value

// GraphQL API details
const graphqlApiUrl = "YOUR_GRAPHQL_API_ENDPOINT>";
const scope = "https://api.fabric.microsoft.com/.default"; // The scope to request the token for

// The GraphQL query
const graphqlQuery = {
  query: `
  <YOUR_GRAPHQL_QUERY>
  `
};

// Function to retrieve a token and call the GraphQL API
async function fetchGraphQLData() {
  try {
    // Step 1: Retrieve token using the ClientSecretCredential
    const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    const tokenResponse = await credential.getToken(scope);
    const accessToken = tokenResponse.token;

    console.log("Access token retrieved!");

    // Step 2: Use the token to make a POST request to the GraphQL API
    const response = await axios.post(
      graphqlApiUrl,
      graphqlQuery,
      {
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json'
        }
      }
    );

    // Step 3: Output the GraphQL response data
    console.log("GraphQL API response:", JSON.stringify(response.data));
    
  } catch (err) {
    console.error("Error:", err.message);
  }
}

// Execute the function
fetchGraphQLData();

A screenshot of a computer program

Description automatically generated

In conclusion, the introduction of Service Principal Names (SPNs) support for the API for GraphQL in Microsoft Fabric marks a significant advancement in enterprise-grade security and authentication. This new feature allows businesses to implement robust application-to-GraphQL authentication without relying on direct user credentials access to data sources, facilitating automated processes and streamlining the management of complex applications. By leveraging SPNs, organizations can enhance their security posture, apply the principle of least privilege, and gain valuable insights into data access patterns. We encourage developers to explore and integrate the new service principal support in their next application based on Microsoft Fabric data to experience the benefits firsthand.

Susiję tinklaraščio įrašai

Adding more flexibility to your business applications with support for Service Principal Names (SPNs) in Fabric API for GraphQL

spalio 31, 2024 – Jovan Popovic

Fabric Data Warehouse is a modern data warehouse optimized for analytical data models, primarily focused on the smaller numeric, datetime, and string types that are suitable for analytics. For the textual data, Fabric DW supports the VARCHAR type that can store up to 8KB of text, which is suitable for most of the textual values … Continue reading “Announcing public preview of VARCHAR(MAX) and VARBINARY(MAX) types in Fabric Data Warehouse”

spalio 29, 2024 – Dandan Zhang

Managed private endpoints allow Fabric experiences to securely access data sources without exposing them to the public network or requiring complex network configurations. We announced General Availability for Managed Private Endpoint in Fabric in May of this year. Learn more here: Announcing General Availability of Fabric Private Links, Trusted Workspace Access, and Managed Private Endpoints. … Continue reading “APIs for Managed Private Endpoint are now available”