a close-up of a building

Nodejs - Azure AD application access token

Microsoft Identity is a cloud-based identity and access management solution that provides secure sign-in and authorization to applications and services. Azure AD is a cloud-based directory and identity management service that enables users to sign in and access applications and services.



Authenticate against the SharePoint Online APIs using Nodejs, Azure AD app and a certificate.


Here is how to do it. Note: I use Node v19, where fetch is an available API.


const jwt = require("jsonwebtoken")
const fs = require("fs")
const crypto = require('crypto')


const safeBase64EncodedThumbprint = (thumbprint) => {
var numCharIn128BitHexString = 128/8*2
var numCharIn160BitHexString = 160/8*2
var thumbprintSizes = {}
thumbprintSizes[numCharIn128BitHexString] = true
thumbprintSizes[numCharIn160BitHexString] = true
var thumbprintRegExp = /^[a-f\d]*$/
var hexString = thumbprint.toLowerCase().replace(/:/g, '').replace(/ /g, '')
if (!thumbprintSizes[hexString.length] || !thumbprintRegExp.test(hexString)) {
throw 'The thumbprint does not match a known format'
}
var base64 = (Buffer.from(hexString, 'hex')).toString('base64')
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
}

async function getAccessTokenWithCert() {
const clientId = "3382fc16-0886-4a21-b7c0-6831efb110ac"
const tenantId = "871527ad-40c5-4400-8e5e-8d5c71f283cb"
const resource = "https://veling.sharepoint.com"
const certificateFile = fs.readFileSync("/Users/velingeorgiev/Documents/ocr/orcpdfsharepoint/certs/newcertificate.pem", "utf-8")
const X509Certificate = crypto.X509Certificate
const x509 = new X509Certificate(certificateFile)
const thumbprint = x509.fingerprint

const options = {
header: {
alg: "RS256",
typ: "JWT",
x5t: safeBase64EncodedThumbprint(thumbprint),
kid: thumbprint.toUpperCase().replace(/:/g, '').replace(/ /g, '')
},
expiresIn: "1h",
audience: `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
issuer: clientId,
subject: clientId,
notBefore: Math.floor(Date.now() / 1000) + 60,
jwtid: '22b3bb26-e046-42df-9c96-65dbd72c1c81'
}

const privateKey = fs.readFileSync("/Users/velingeorgiev/Documents/ocr/orcpdfsharepoint/certs/privatekey.pem", "utf-8")

const token = jwt.sign({}, privateKey, options)

const response = await fetch(
`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: `grant_type=client_credentials&client_id=${clientId}&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion=${token}&scope=${`${resource}/.default`}` //&resource=${resource}
}
);
return response.json().then(data => {
console.log(data)
return data.access_token
})
}


Create a self-signed certificate using OpenSSL


  1. Install OpenSSL on your system if it's not already installed.
  2. Open a command prompt or terminal window and navigate to the directory where you want to store the certificate.
  3. Generate a private key using the following command:


openssl genpkey -algorithm RSA -out private.pem -outform PEM


or with a private key with a password


openssl genpkey -algorithm RSA -out private.pem -aes256 -outform PEM


  1. Generate a self-signed certificate using the private key:


openssl req -new -x509 -key private.pem -out certificate.pem


  1. During the certificate generation process, OpenSSL will ask for some information, such as the country name, state or province, city, and so on. Fill in the required information. The common name field should be the fully qualified domain name (FQDN) of the server where the certificate will be used.
  2. The certificate.pem file will now contain your self-signed certificate. You can use this certificate to secure your website or other applications.
  3. If you need to convert the certificate to other formats, such as PFX or DER, you can use the following commands:


// Convert to PFX
openssl pkcs12 -export -out certificate.pfx -in certificate.pem -inkey private.pem


// Convert to DER
openssl x509 -outform der -in certificate.pem -out certificate.der


Note: Self-signed certificates are not trusted by default and can cause security warnings in web browsers. In production environments, it's recommended to use a trusted certificate authority (CA) to issue certificates.


Upload the self-signed certificate to the Azure AD Application.



To upload a PEM certificate to an Azure Active Directory (AD) application, you can use the Azure portal, Azure CLI, or Azure PowerShell. Here's a brief overview of the steps for each method.


Using the Azure portal:


  1. Log in to the Azure portal and navigate to the Azure AD application for which you want to upload the certificate.
  2. Select the "Certificates and secrets" option from the navigation menu.
  3. Click the "Upload certificate" button to select the PEM certificate file.
  4. Enter a description for the certificate, and then click the "Add" button to upload the certificate.



Registering an Application in Azure AD


To authenticate an application with Microsoft Identity and Azure AD, you need to register the application in the Azure AD portal. This process creates a unique identifier for the application and generates the necessary credentials that the application will use to authenticate with Microsoft Identity.


To register an application in Azure AD:


  1. Log in to the Azure portal and select Azure Active Directory.
  2. Select App registrations and then New registration.
  3. Provide a name for the application and select the appropriate, supported account types.
  4. Provide a redirect URI for the application, which is the URL that the user will be redirected to after they sign in.
  5. Click Register to create the application.



Granting Delegated Permissions


In order to access resources on behalf of the signed-in user, the application needs to be granted delegated permissions. Delegated permissions allow an application to access resources as the signed-in user, with the user's consent.


To grant delegated permissions to an application:


  1. Select the application you just registered from the list of app registrations.
  2. Select API permissions and then Add permission.
  3. Select the API that you want to grant permissions to, such as Microsoft Graph.
  4. Select the permissions that you want to grant the application.
  5. Click Add permissions to grant the selected permissions to the application.



Conclusion


Authentication in Microsoft Identity with Azure AD and application delegated permissions enables you to secure access to resources for your applications and services. By registering the application in Azure AD, granting delegated permissions, and authenticating the application, you can ensure that your applications are secure and your data is protected.