In the previous lessons we have repeated one idea: in SaaS the infrastructure and the code disappear, but identities, integrations, licenses and data still belong to the customer. This lesson deals with precisely that. When a company moves from a mail server to a SaaS suite, and then adds a CRM, an HR tool and half a dozen more applications, questions appear that did not exist before: how many passwords does each employee have?, what happens to the accounts of a sales rep who leaves the company?, how does the warehouse find out about a deal closed in the CRM?, who is paying for the licenses of someone who has not signed in for three months?, which applications are employees using without anyone knowing? In this lesson you will learn how to centralise identity in Entra ID with single sign-on (SAML 2.0 and OpenID Connect), MFA and Conditional Access; how to automate joiners and leavers with SCIM; how to integrate SaaS applications with APIs, OAuth 2.0, webhooks and iPaaS tools; and how to govern the whole estate: inventory, licenses, permissions, sharing, backups and exit plan. You will finish with Hortalia's governance matrix.

  1. A central identity provider

Without an identity strategy, every SaaS product has its own base of users and passwords. With five applications and 120 employees, that is 600 accounts to create, protect and, above all, disable in time. The solution is a central identity provider (IdP): a single place where identities live and that "lends" authentication to every application.

Concept What it is At Hortalia
Identity provider (IdP) The system that authenticates users and issues proof of identity Microsoft Entra ID (already used for Azure and the sales reps' VPN)
Service provider (SP) or relying application The application that trusts the IdP instead of managing passwords of its own The CRM, Microsoft 365, the HR tool
Federation The trust relationship between the IdP and the application (certificates, addresses, identifiers) Configured once per application
Single sign-on (SSO) The user authenticates once with the IdP and reaches every federated application A sales rep signs in to the CRM with their @hortalia.example account

Hortalia starts with an advantage: Entra ID is the same directory that Microsoft 365 uses, so by choosing that suite the 120 email identities are already in the IdP. If Hortalia keeps an on-premises Active Directory in the warehouse, the identities are synchronised with Entra ID through Microsoft Entra Connect or Cloud Sync; how and when to retire that local directory is a migration decision covered in Cloud Migration.

  1. Single sign-on: SAML 2.0 and OpenID Connect

There are two main protocols for SSO with SaaS applications:

Aspect SAML 2.0 OpenID Connect (OIDC)
Year and origin 2005, designed for enterprises and browsers 2014, built on top of OAuth 2.0
Format of the proof of identity A signed XML assertion An ID token in JWT format (signed JSON)
Transport HTTP redirects and POST forms in the browser HTTP redirects and calls with JSON
Typical use "Classic" enterprise SaaS Modern applications, mobile, APIs
Configuration XML metadata, signing certificate, identifier and reply URL (ACS) Client ID, secret or certificate, redirect URL, scopes

For the user the result is the same: they click "Sign in with Microsoft" (or simply open the application) and, if they already have a session with Entra ID, they get in without typing the password again.

2.1 How a SAML sign-in works

Let us look at the most common flow, started from the application (SP-initiated), when a sales rep opens the CRM:

sequenceDiagram
    participant U as Sales rep (browser)
    participant SP as SaaS CRM (service provider)
    participant IdP as Entra ID (identity provider)
    U->>SP: 1. Opens the CRM address
    SP-->>U: 2. Redirects to Entra ID with a SAML request
    U->>IdP: 3. Delivers the SAML request
    IdP-->>U: 4. Asks for password and MFA (and evaluates Conditional Access)
    U->>IdP: 5. Authenticates
    IdP-->>U: 6. Returns a signed SAML assertion
    U->>SP: 7. Sends the assertion (POST to the ACS URL)
    SP->>SP: 8. Verifies the signature with Entra ID's certificate
    SP-->>U: 9. Signed in to the CRM

An explanation of each step:

  1. The sales rep opens the CRM in the browser.
  2. The CRM does not have their password and does not want it: it redirects them to Entra ID with a request that says "authenticate this user for me".
  3. The browser takes that request to Entra ID. Notice that the CRM and Entra ID never talk to each other directly: everything goes through the browser.
  4. Entra ID checks whether the user already has a session. If not, it asks for a password and a second factor, and evaluates the Conditional Access policies (section 3): from where, with which device, at what risk.
  5. The sales rep authenticates.
  6. Entra ID generates an assertion: an XML document that says "this user is [email protected], authenticated at 9:02 with MFA", signed with its private key.
  7. The browser sends the assertion to the CRM's receiving address, known as the ACS (Assertion Consumer Service).
  8. The CRM verifies the signature with Entra ID's public certificate, configured when the federation was created. If anyone altered the assertion, the signature would not match.
  9. The CRM opens the session for the user identified by the assertion.

In OpenID Connect the scheme is very similar: instead of an XML assertion, the application receives (usually in exchange for a one-time code) a signed JWT ID token with the user's data.

The practical consequence is enormous: the password is only ever typed into Entra ID, security policies are applied in a single place and, when an account is disabled in Entra ID, the user can no longer get into any federated application. Two warnings: many SaaS products only offer SSO in their higher plans (the "SSO tax" from Popular SaaS Providers), and it is wise to keep an emergency administrator account in each SaaS product that does not depend on SSO, so that you can get in if the federation fails.

  1. MFA and Conditional Access

Multi-factor authentication (MFA) requires something you know (a password) and something you have (a phone with an authenticator app, a security key) or are (biometrics). Remember the incident in The Shared Responsibility Model: SaaS email without MFA, a password stolen by phishing and fake invoices sent to customers.

Conditional Access goes one step further: these are "if... then..." rules that Entra ID evaluates at every sign-in. It requires Entra ID P1, included in the Business Premium and F3 licenses of Hortalia's prototype (check the details of the plan). Laura designs these initial policies:

Policy If... Then... Reason
MFA for everyone Any user accesses any application Require MFA The minimum baseline against password theft
Block legacy authentication A client uses old protocols (POP, IMAP with basic passwords, etc.) Block Legacy protocols do not support MFA
Hardened administrators A user with an admin role signs in Require phishing-resistant MFA (a FIDO2 key or similar) Admin accounts are the prime target
Sales reps' phones A sales rep opens email or the CRM from a phone Require a protected app or a device managed with Intune If they lose the phone, company data can be wiped
Unexpected locations A sign-in from countries where Hortalia does not operate Block or require additional MFA Reduces automated attacks
Sign-in risk Entra ID detects a high-risk sign-in Block or require a password change Requires Entra ID P2; Laura notes it down as an improvement

Tip: Conditional Access policies are first tested in report-only mode (they log what they would have done without enforcing it) and the emergency accounts are always excluded, so that a mistake does not lock out the whole organisation.

  1. Automatic provisioning with SCIM

SSO solves how the user gets in, but not whether they exist in the application. If Laura has to create each user by hand in the CRM, the HR tool and the rest, we are back to the problem of the 600 accounts. The SCIM standard (System for Cross-domain Identity Management, version 2.0) defines a common REST API so that the IdP can create, modify and deactivate users in applications automatically.

In Entra ID it is configured in the corresponding enterprise application: Laura specifies which groups the application is assigned to (for example, "Sales team") and Entra ID takes care of creating accounts in the CRM for its members. When somebody joins the group, Entra ID sends a request like this one:

POST /scim/v2/Users HTTP/1.1
Host: api.crm-example.example
Authorization: Bearer <crm-scim-token>
Content-Type: application/scim+json

{
  "schemas": [
    "urn:ietf:params:scim:schemas:core:2.0:User",
    "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
  ],
  "externalId": "7d1e5c0a-3f2b-4c55-9a10-0c8e4b2f1a77",
  "userName": "[email protected]",
  "name": { "givenName": "Marta", "familyName": "Soler" },
  "emails": [ { "value": "[email protected]", "type": "work", "primary": true } ],
  "title": "Sales rep",
  "active": true,
  "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
    "department": "Sales",
    "manager": { "value": "[email protected]" }
  }
}

Explanation:

  • POST /scim/v2/Users: create a user in the standard Users resource. The specific address is published by each SaaS product; an example domain is used here.
  • Authorization: Bearer ...: the token the SaaS product gives the administrator so that Entra ID can call its SCIM API. It is stored in Entra ID's provisioning configuration, not in any document.
  • schemas: declares which schemas the message uses: the user core and the enterprise extension (department, manager).
  • externalId: the user's identifier in Entra ID. It allows them to be recognised even if their email address changes.
  • userName, name, emails, title: the basic attributes, which Entra ID takes from the directory according to a configurable attribute mapping.
  • active: true: the account is enabled. This field is the most important one in the lifecycle.
  • The enterprise extension: department and manager, useful so that the CRM can assign teams.

When the person leaves the group or their account is disabled, Entra ID sends a PATCH that sets active to false:

{
  "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
  "Operations": [ { "op": "replace", "path": "active", "value": false } ]
}

Most SaaS products deactivate the account rather than deleting it, so as to keep the history. Just like SSO, SCIM is usually only available in enterprise plans; with the free CRM plan that Hortalia is using as a prototype, joiners and leavers will be handled manually, and that is one more argument to weigh in the module 5 decision.

  1. Joiners, movers and leavers: when a sales rep leaves the company

The lifecycle of an identity boils down to three moments, known as joiner-mover-leaver:

Moment What happens What must happen in the SaaS products
Joiner A new person arrives An account in Entra ID, groups according to their role, licenses assigned by group, accounts created through SCIM, MFA registered on day one
Mover They change role or department A change of groups: they gain the access of the new role and lose that of the previous one
Leaver They leave the company Immediate block, session revocation, deactivation in every SaaS product, handover of their data and release of licenses

The critical moment is the leaver. Imagine that Marta, a sales rep, leaves Hortalia on a Friday. This is the procedure Laura documents:

flowchart TD
    A["HR reports the departure<br/>(date and time)"] --> B["Laura blocks the account in Entra ID<br/>and revokes active sessions"]
    B --> C["SSO: Marta can no longer get into<br/>any federated application"]
    B --> D["SCIM deactivates her user<br/>in the CRM (or Laura does it by hand)"]
    D --> E["Jordi receives her companies,<br/>contacts and deals from the CRM"]
    B --> F["Her mailbox becomes shared<br/>with access for Jordi for 90 days"]
    B --> G["Remote wipe of company data<br/>from the phone (Intune)"]
    F --> H["The Business Premium license is released"]
    E --> I["Review: did she have accounts in<br/>non-federated SaaS? API tokens?"]

Important details:

  • Revoking sessions is as important as blocking the account: without it, sessions already open on a phone can stay alive for a while.
  • Hand over the data before deleting: in the CRM, Marta's companies and deals are reassigned to Jordi (or to another sales rep) so that no customer is left orphaned. Compared with the spreadsheet, this is one of the CRM's great advantages.
  • The mailbox: turning it into a shared mailbox preserves its contents and lets Jordi answer customer emails without keeping a paid license (within the size limits for shared mailboxes).
  • What the IdP cannot see: if Marta signed herself up to a SaaS tool with her work email and a password of her own, blocking Entra ID does not throw her out of that tool. That is why the application inventory in section 9 matters.

  1. Integration: REST APIs and OAuth 2.0

In Definition and Characteristics of SaaS we saw a minimal call to a CRM's API. Let us now see how an application is authorized to call a SaaS product's API.

6.1 Tokens and scopes

The vast majority of SaaS products use OAuth 2.0, an authorization standard: instead of giving an application your username and password, the SaaS product hands it an access token with limited permissions (the scopes) and an expiry date.

Concept What it is Example
Access token A temporary credential sent with every call (Authorization: Bearer ...) Valid, for example, for one hour
Refresh token Allows new access tokens to be obtained without asking the user again Stored securely on the server
Scope A specific permission that is granted crm.objects.contacts.read (read contacts), User.Read.All (read users in Microsoft Graph)
Consent Explicit acceptance of the scopes by the user or the administrator The "This application wants to access..." screen

6.2 The most common flows

Flow Who acts When it is used Example at Hortalia
Authorization code (with PKCE) An application on behalf of a user Integrations that act with the permissions of the person who connects them The CRM's Outlook extension reads the email of the sales rep who installs it
Client credentials An application in its own name, with no user Automated server-side processes The license review script in section 10
Private app token or API key An internal integration with a fixed token created by an administrator Simple integrations with a single SaaS product The function in section 8 queries the CRM

Golden rules, which Marc already applied with the store's secrets in module 3:

  • Least privilege: ask only for the scopes you really need. An integration that only reads deals does not need permission to delete contacts.
  • Tokens are secrets: never in the code or in the repository; in Key Vault or in the platform's protected configuration.
  • Rotation: fixed tokens are renewed periodically and whenever someone with access to them leaves the company.
  • Review the consents: users can grant third-party applications access to their data; Laura will restrict user consent in Entra ID so that new applications require administrator approval.

  1. Webhooks, connectors and iPaaS

7.1 Webhooks: the SaaS product tells you

Polling an API every few minutes to see whether "something has happened" is inefficient. With a webhook, the SaaS product makes an HTTP POST request to an address you give it when an event occurs. For example, this is the (simplified) format HubSpot uses to report that a property of a deal has changed:

[
  {
    "eventId": 3816279340,
    "subscriptionId": 25,
    "portalId": 145001234,
    "appId": 3000001,
    "occurredAt": 1789551720000,
    "subscriptionType": "deal.propertyChange",
    "attemptNumber": 0,
    "objectId": 9012345678,
    "propertyName": "dealstage",
    "propertyValue": "closedwon",
    "changeSource": "CRM"
  }
]

An explanation of the fields:

  • It is a list ([...]): the SaaS product can group several events into a single request; the receiver must go through all of them.
  • eventId: the event's unique identifier. It is there so that it is not processed twice if it arrives more than once.
  • portalId: the identifier of Hortalia's account (the tenant) in the CRM.
  • occurredAt: when it happened, in milliseconds since 1970 (Unix time format).
  • subscriptionType: the type of event. Here, a change to a deal property.
  • objectId: the identifier of the deal affected.
  • propertyName / propertyValue: which property changed and to what value. closedwon is the internal identifier of the "Won" stage in the default pipeline.
  • attemptNumber: the retry number. If the receiver does not respond successfully, the SaaS product retries for a while.

Notice what it does not bring: the deal's amount. Many webhooks only send "what changed" and the receiver has to query the API for the rest. We will see this in section 8.

7.2 Connectors and iPaaS versus building your own integration

In Types of PaaS we introduced integration platform as a service (iPaaS). For SaaS they are very common, because they offer ready-made connectors for hundreds of applications.

Option Examples Advantages Drawbacks When to choose it
The SaaS product's native integration "Connect to Outlook" in the CRM Zero development Only what the provider offers Whenever it exists and covers the need
iPaaS / no-code automation Power Automate, Zapier, Make, Logic Apps Fast, no programming, visual Cost per run or per user; complex logic is hard; one more SaaS product to govern Simple flows between popular SaaS products
Your own integration An Azure function, an API on App Service Total control, complex logic, code in the repository You have to write and maintain it Bespoke logic, internal systems (such as the ERP), high volumes

At Hortalia, the stock API that Marc built on PaaS is an example of a bespoke integration: the legacy ERP has no connectors in any iPaaS, so the only way to expose its stock securely is a façade API. For the large-order alert, on the other hand, both options would work. Power Automate is partly included in the Microsoft 365 licenses (with standard connectors; the premium ones require extra licenses), but Marc prefers the function because he already maintains func-hortalia-tareas and the logic will sit alongside the rest of his code.

  1. Example: from a deal won in the CRM to an Azure function

Goal: when a sales rep marks a deal of €3,000 or more as "Won", the warehouse needs to know so that it can plan stock. Today the sales rep phones in (when they remember to).

flowchart LR
    A["Sales rep marks<br/>the deal as Won"] --> B["The CRM sends a webhook<br/>(deal.propertyChange)"]
    B --> C["func-hortalia-tareas<br/>HTTP function deal_ganado"]
    C --> D["Queries the amount<br/>in the CRM's API"]
    D --> E{"Amount >= €3,000?"}
    E -- Yes --> F["Logs it and emails<br/>the warehouse"]
    E -- No --> G["Only logs it"]

Marc adds a function with an HTTP trigger to the func-hortalia-tareas application from module 3:

import base64
import hashlib
import hmac
import json
import logging
import os
import time

import azure.functions as func
import requests
from azure.communication.email import EmailClient

app = func.FunctionApp()  # in the real project, this is the same "app" as listado_almacen

THRESHOLD_EUR = 3000


def valid_signature(req: func.HttpRequest) -> bool:
    """Check that the request comes from the CRM (HubSpot v3 signature)."""
    signature = req.headers.get("X-HubSpot-Signature-v3", "")
    stamp = req.headers.get("X-HubSpot-Request-Timestamp", "0")
    if abs(time.time() * 1000 - int(stamp)) > 5 * 60 * 1000:
        return False  # more than 5 minutes old: possible malicious replay
    text = req.method + req.url + req.get_body().decode("utf-8") + stamp
    computed = base64.b64encode(
        hmac.new(os.environ["CRM_CLIENT_SECRET"].encode(), text.encode(),
                 hashlib.sha256).digest()
    ).decode()
    return hmac.compare_digest(computed, signature)


@app.route(route="crm/deal-ganado", methods=["POST"], auth_level=func.AuthLevel.FUNCTION)
def deal_ganado(req: func.HttpRequest) -> func.HttpResponse:
    if not valid_signature(req):
        logging.warning("Webhook rejected: invalid signature")
        return func.HttpResponse(status_code=401)

    for event in req.get_json():
        if event.get("propertyName") != "dealstage" or event.get("propertyValue") != "closedwon":
            continue
        deal_id = event["objectId"]
        response = requests.get(
            f"https://api.hubapi.com/crm/v3/objects/deals/{deal_id}",
            params={"properties": "dealname,amount"},
            headers={"Authorization": f"Bearer {os.environ['CRM_TOKEN']}"},
            timeout=10,
        )
        response.raise_for_status()
        data = response.json()["properties"]
        amount = float(data.get("amount") or 0)
        logging.info("Deal won %s (%s): %.2f EUR", deal_id, data["dealname"], amount)

        if amount >= THRESHOLD_EUR:
            EmailClient.from_connection_string(os.environ["ACS_CONNECTION_STRING"]).begin_send({
                "senderAddress": os.environ["REMITENTE"],
                "recipients": {"to": [{"address": os.environ["DESTINO_ALMACEN"]}]},
                "content": {
                    "subject": f"Large order won: {data['dealname']} ({amount:,.0f} EUR)",
                    "plainText": "Please check the expected stock for this customer.",
                },
            }).result()

    return func.HttpResponse(status_code=200)

An explanation block by block:

  • Imports: hmac, hashlib and base64 are there to verify the signature; requests to call the CRM's API; EmailClient is the same Azure Communication Services email client we used in the 6:00 listing function.
  • valid_signature: the function's address is on the internet, so anyone could send it a fake JSON payload. HubSpot signs every request: it calculates an HMAC-SHA256 of method + URL + body + timestamp with the application's secret and sends it in the X-HubSpot-Signature-v3 header. The function repeats the calculation with the same secret and compares. hmac.compare_digest compares in constant time so as not to give an attacker any hints. If the timestamp is more than five minutes old, the request is rejected to prevent old requests being replayed. (Behind some proxies the URL the function sees may differ from the one the sender signed; if verification always fails, check that point and the provider's current documentation.)
  • @app.route(... auth_level=func.AuthLevel.FUNCTION): creates an HTTP endpoint POST /api/crm/deal-ganado that also requires a function key in the URL. It is a second barrier, not a replacement for the signature.
  • The for event in req.get_json() loop: goes through all the events in the batch and discards those that are not "stage changed to Won".
  • The API call: since the webhook does not bring the amount, the function asks for the deal with GET /crm/v3/objects/deals/{id} and only the dealname and amount properties. The token (CRM_TOKEN) only needs the deal-read scope.
  • float(data.get("amount") or 0): the amount arrives as text and may be empty if the sales rep did not fill it in; in that case 0 is used.
  • The alert: if it is above the threshold, an email is sent to the warehouse. In every case a line is left in the logs (Application Insights), which is the record of the event.
  • return func.HttpResponse(status_code=200): responding quickly with success tells the CRM not to retry. If the function failed, the CRM would retry; that is why, in a real system, the eventId would be stored so as not to alert twice about the same order.

All the secrets (CRM_CLIENT_SECRET, CRM_TOKEN, ACS_CONNECTION_STRING) go into the function's configuration as Key Vault references, just as in module 3. One warning about the prototype: subscribing to webhooks requires registering an application in the CRM's developer account, and the exact way to do it (public, private or project-based application) and its availability by plan change over time; check the current documentation. If it were not available, the alternative is a CRM automation workflow (on paid plans) or Power Automate polling the CRM periodically.

  1. Governance 1: application inventory and shadow IT

Signing up for a SaaS product is so easy (a credit card and an email address) that applications proliferate without control. Shadow IT is the name given to applications used in the company without IT's knowledge or approval: the sales rep who keeps customer records in a free notes app, the department that buys its own survey tool, the person who connects an AI extension to their mailbox.

Risks: customer data out of control, accounts that are never disabled, duplicate licenses, data protection breaches.

How to discover them:

Source What it reveals Comment
Entra ID sign-in logs Which federated applications are used and by whom Only sees applications connected to Entra ID
Application consents (OAuth) Third-party applications that users have given access to their email or files Review under "Enterprise applications"; restrict user consent
Microsoft Defender for Cloud Apps or other CASB solutions SaaS discovery from network traffic or from devices Requires specific licenses; useful above a certain size
Card spending and invoices Subscriptions paid for by departments Sara can look for recurring charges from software vendors
A survey of the managers Free tools that leave no financial trace Simple and surprisingly effective

The goal is not to ban but to know and channel: an application inventory with its owner, its data and its status (approved, under evaluation, banned), and a simple procedure for requesting a new one. If asking for a tool takes three weeks, people will keep using them behind your back.

  1. Governance 2: licenses, roles and external sharing

10.1 Licenses: spotting the ones nobody uses

With licenses charged per user per month, every forgotten license is money lost every month. The typical review looks for licensed users who have not signed in recently. Laura automates that review with Microsoft Graph, the unified API for Microsoft 365 and Entra ID (the old MSOnline and AzureAD PowerShell modules have been retired; Graph is the current path).

First, a quick summary of licenses purchased and assigned, using the Microsoft Graph SDK for PowerShell:

Connect-MgGraph -Scopes "Organization.Read.All"
Get-MgSubscribedSku | Select-Object SkuPartNumber, ConsumedUnits,
    @{ Name = "Purchased"; Expression = { $_.PrepaidUnits.Enabled } }
  • Connect-MgGraph -Scopes ...: signs in asking only for read permission on the organisation.
  • Get-MgSubscribedSku: returns each license type in the tenant. SkuPartNumber is the technical name (for example, SPB corresponds to Business Premium; the technical names are not always intuitive, check Microsoft's reference table), ConsumedUnits the assigned ones and PrepaidUnits.Enabled the purchased ones. If Hortalia has bought 45 and assigned 41, it is paying for 4 that nobody uses.

Next, the script that looks for inactive users. It runs as an application registered in Entra ID with the application permissions User.Read.All and AuditLog.Read.All (the signInActivity property also requires Entra ID P1 or higher licenses in the tenant):

import os
from datetime import datetime, timedelta, timezone

import msal
import requests

INACTIVITY_DAYS = 60
GRAPH = "https://graph.microsoft.com/v1.0"

# 1. Get an application token (client credentials flow)
client = msal.ConfidentialClientApplication(
    client_id=os.environ["GRAPH_CLIENT_ID"],
    client_credential=os.environ["GRAPH_CLIENT_SECRET"],
    authority=f"https://login.microsoftonline.com/{os.environ['TENANT_ID']}",
)
token = client.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
headers = {"Authorization": f"Bearer {token['access_token']}"}

# 2. Translate the license identifiers into readable names
skus = requests.get(f"{GRAPH}/subscribedSkus", headers=headers, timeout=30).json()["value"]
sku_name = {s["skuId"]: s["skuPartNumber"] for s in skus}

# 3. Go through every user, page by page
url = (f"{GRAPH}/users?$select=displayName,userPrincipalName,accountEnabled,"
       "assignedLicenses,signInActivity&$top=100")
cutoff = datetime.now(timezone.utc) - timedelta(days=INACTIVITY_DAYS)

while url:
    page = requests.get(url, headers=headers, timeout=30).json()
    for u in page["value"]:
        if not u["assignedLicenses"]:
            continue  # no license: it costs us nothing
        activity = u.get("signInActivity") or {}
        dates = [activity.get("lastSignInDateTime"),
                 activity.get("lastNonInteractiveSignInDateTime")]
        dates = [datetime.fromisoformat(d.replace("Z", "+00:00")) for d in dates if d]
        last = max(dates) if dates else None
        if last is None or last < cutoff:
            licenses = ", ".join(sku_name.get(l["skuId"], l["skuId"])
                                 for l in u["assignedLicenses"])
            when = last.date() if last else "never"
            print(f"{u['userPrincipalName']:40} last sign-in: {when}  licenses: {licenses}")
    url = page.get("@odata.nextLink")  # next page, or None if there are no more

An explanation step by step:

  • Step 1: msal is Microsoft's official library for obtaining tokens. With the client credentials flow (section 6), the application authenticates with its own identifier and secret, with no user involved. The .default scope means "the application permissions the administrator has already granted". The secret comes from an environment variable; in production, a certificate or a managed identity is better.
  • Step 2: each user's licenses arrive as identifiers (GUIDs). subscribedSkus lets them be translated into technical names such as SPB.
  • Step 3: $select asks only for the properties needed (less data, faster). signInActivity holds the dates of the last interactive sign-in (the user typed their password or used MFA) and the last non-interactive one (an application renewed its session, such as Outlook on a phone). The script takes the more recent of the two so as not to flag someone who only uses their phone as inactive.
  • @odata.nextLink: Graph returns results in pages; as long as that link exists, there are more users to read.
  • The output lists licensed users with no activity in 60 days (or who have never signed in). The names and the exact behaviour of these properties may evolve: check the current Microsoft Graph documentation before using this in production.

The script only reports; it does not remove licenses. The decision is Laura's, together with each person's manager (it could be sick leave, not someone leaving the company). To reassign, the cleanest approach is Entra ID's group-based licensing: the license is assigned to the "Office" or "Frontline" group and it is enough to move the person from one group to the other. For one-off cases there is Set-MgUserLicense in the PowerShell SDK.

10.2 Roles and permissions

  • Administrators of the suite: few, and with specific roles. In Microsoft 365, instead of giving everyone the global administrator role, scoped roles are used (Exchange administrator, user administrator, billing administrator). A common recommendation: between two and four global administrators, including the emergency accounts.
  • Roles in the CRM: Jordi, as head of sales, sees the whole team; each sales rep sees their own customers and those of their team; customer service has read-only access to contact details. The granularity available depends on the plan.
  • Periodic review: permissions pile up as people change roles. A quarterly review of who has what stops someone ending up with the access rights of three previous jobs.

10.3 External sharing

In SaaS, sharing with somebody outside is one click away. Laura configures:

Setting Initial configuration at Hortalia Reason
"Anyone with the link" links on files Disabled Stops customer lists ending up behind public links
Sharing with guests Only with authenticated guests and with an expiry date Suppliers and advisers do need documents
Automatic email forwarding to external addresses Blocked (with approved exceptions) A common technique after an account is stolen (The Shared Responsibility Model)
Teams teams with guests Only if the team owner requests it Keeps control of which teams have external members
Bulk exports in the CRM Administrators only A sales rep who leaves should not be able to take the customer base away in a CSV

  1. Governance 3: backups, export and exit plan

11.1 The provider does not always protect you from yourself

A frequent mistake is thinking that "SaaS already does backups". The provider replicates the data so that a failure in its data centers does not lose it, but that does not protect against:

  • An accidental deletion by a user (the deletion is replicated).
  • A malicious deletion by a disgruntled employee or by an attacker with a stolen account.
  • Ransomware that encrypts synchronised files.
  • An integration bug that overwrites thousands of CRM records.
Protection layer What it offers Limit
The SaaS product's recycle bins and versions Recovering deleted items or earlier versions for a period of time Limited windows (days or weeks, depending on the product)
Retention policies Keeping content for a defined period even if it is deleted Useful for compliance; bulk restores are not always straightforward
The provider's own backup (an extra service) Some suites offer backup services with restore, at extra cost The data is still with the same provider
Third-party backup Specialised tools that copy the SaaS product to other storage Extra cost; the copy sits outside the provider (the 3-2-1 rule)
Your own periodic exports CSV files or CRM API output stored in Hortalia's own storage They have to be automated and proved to work

For Hortalia, Laura proposes: 7-year retention for the shared orders mailbox (to be validated with the advisers, see Security and Compliance), evaluating a third-party backup for email and OneDrive, and a weekly export of the CRM through the API to the Azure storage account with immutability, reusing what was learned with the ERP backups in module 2.

11.2 Export and exit plan

The exit plan answers a simple question: if we had to leave this SaaS product tomorrow, how would we do it? For each significant SaaS product, Laura documents:

  1. What data there is (contacts, companies, deals, activities, attachments, history).
  2. How it is exported (CSV from the interface, API, migration tool) and when it was last tested.
  3. What is lost in the export (configuration, automations, reports).
  4. Contractual timeframes after cancellation: how long the provider keeps the data and when it deletes it.
  5. Alternatives identified.

Migration strategies and vendor lock-in are studied in depth in Cloud Migration: Strategies and Vendor Lock-in; here the rule is enough: no SaaS product goes into production without a tested export.

  1. Hortalia: the SaaS governance matrix

Laura presents management with a governance matrix for the current and planned SaaS products. She distinguishes the business owner (who decides what is done with the tool and who uses it) from the technical administrator (who configures security, identities and integrations).

SaaS Status Business owner Technical administrator Users SSO / provisioning Sensitive data License review Backup / export
Microsoft 365 (email, Teams, OneDrive) Prototype General management Laura 120 (45 + 75) Native (Entra ID) Email with customers and suppliers Quarterly, Graph script Retention + third-party backup (under evaluation)
CRM (HubSpot, free plan) Prototype Jordi Laura (with Jordi as functional administrator) 9 Manual on the free plan; SSO/SCIM depending on the paid plan Personal data of individual customers Quarterly, manual Weekly export through the API
Azure (platform, not SaaS) In use Laura Laura / Marc The technical team Entra ID Everything in the ERP and the store Budgets and alerts (Sara) Backups of the ERP and the store's database
Other applications discovered To be inventoried The manager of the area using it Laura Variable To be reviewed To be reviewed To be reviewed To be reviewed

And a three-rule procedure for new applications:

  1. Anyone can propose an application with a short form (what for, who, what data, cost).
  2. Laura reviews security, identity, data location and export with the checklist from Popular SaaS Providers; Sara approves it if there is a cost; if it processes personal data, the person responsible for data protection is consulted as well.
  3. A quarterly review (Laura, Sara and the business owners): unused licenses, access rights of people who changed roles, new applications discovered, renewal dates coming up and the date of the last export test.

Warning: the examples in this lesson (Conditional Access policies, webhook verification, Graph scripts, sharing settings) are for teaching purposes. Before applying them in a real environment, they should be reviewed with a security professional and checked against each provider's current documentation, which changes frequently.

Common Mistakes and Tips

  • Switching on SSO without an emergency account. If the federation fails or the certificate expires, nobody will be able to get in. Keep a local administrator account in each SaaS product, with strong MFA, stored securely.
  • Letting the SAML signing certificate expire. It has an expiry date; write it down and set up reminders.
  • Disabling the account in Entra ID and forgetting the rest. Local accounts in non-federated SaaS products, API tokens created by the person and the data that "belonged" to them in the CRM each need their own step.
  • Accepting webhooks without verifying the signature. A public URL with no verification is a door for injecting fake events.
  • Tokens with more permissions than necessary, or in the code. Least privilege and a secrets store, always.
  • Confusing replication with backup. A deletion is replicated; only an independent copy or a well-configured retention policy undoes it.
  • Governing through bans. If the approval process is slow, shadow IT grows. A simple, fast procedure protects you more.
  • Tip: start governance with the minimum viable set (inventory, an owner per application, MFA everywhere and a quarterly review) and improve it every quarter.

Exercises

Exercise 1. A Hortalia sales rep becomes a warehouse supervisor (a "mover", not a leaver). List what has to change in Entra ID, Microsoft 365 and the CRM, and explain what risk appears if only the new permissions are added without removing the old ones.

Exercise 2. The function in section 8 has received the same event twice (the same eventId) because the first response took too long and the CRM retried. The warehouse has received two emails about the same order. Propose a solution and describe, in pseudocode or Python, where you would add it.

Exercise 3. The license script in section 10.1 returns five users with no sign-in in 60 days: two seasonal delivery drivers who finished in January, someone in administration on maternity leave, a "formacion@" mailbox created as a licensed user and the emergency account [email protected]. Say what you would do with each one.

Solutions

Solution 1. In Entra ID: remove them from the "Sales team" group and add them to "Warehouse supervisors" (and to the corresponding licensing group; they are still office staff, so they keep Business Premium). In Microsoft 365: leave the Teams teams and lists of the sales area, join the "Warehouse and delivery" team as an owner, and review access to shared mailboxes (they may gain reparto@). In the CRM: reassign their companies and deals to another sales rep and deactivate their user (with SCIM, this would happen automatically when they left the group). The risk of only adding: privilege accumulation; they would still be able to see and export the customer base without needing to, and if their account were compromised, the attacker would have access to the data of two areas. That is the reason for the quarterly access review.

Solution 2. Make the function idempotent: store the eventId values already processed and discard the repeats. For example, in an Azure Table Storage table or in the database:

for event in req.get_json():
    if already_processed(event["eventId"]):   # look it up in the processed events table
        continue
    # ... current logic: filter, query the amount, alert ...
    mark_processed(event["eventId"])          # insert the eventId with the date

It is also worth responding quickly: if the alert is slow, the function can drop the event into a queue (Azure Queue Storage) and respond 200 immediately, processing it afterwards with another function. Common mistake: trying to prevent the sender's retries; retries are a good thing (they guarantee the event arrives), what you have to do is tolerate them.

Solution 3. Seasonal delivery drivers: block the accounts (if it was not done when they left), release the F3 licenses and review the leaver procedure, which has failed. The person on maternity leave: leave it alone; it is a temporary absence (at most, note it down so as not to review it again until they are back). The "formacion@" mailbox: turn it into a shared mailbox and release the license; it is not a person. The emergency account: it is normal for it not to be used; it is excluded from the report, but you check that its MFA works and that its credential is still kept safe (ideally, test it twice a year). Tip: add a documented exclusion list to the script so you do not review the same items every quarter.

Conclusion

In this lesson you have learned that governing SaaS starts with identity: a central identity provider (Entra ID), SSO with SAML 2.0 or OpenID Connect so that the password is only ever typed in one place, MFA and Conditional Access to decide who gets in and from where, and SCIM so that joiners and leavers reach the applications by themselves, with the departure of a sales rep as the critical case. You have seen how SaaS applications are integrated with REST APIs and OAuth 2.0 (tokens, scopes, flows), signed webhooks and iPaaS tools, and you have written a function that receives the alert for a deal won in the CRM, looks up its amount and notifies the warehouse. Finally, you have toured governance: inventory and shadow IT, unused licenses spotted with Microsoft Graph, roles, external sharing, backups that protect you from your own mistakes and the exit plan, all summed up in Hortalia's governance matrix.

The time has come to move from theory to practice. In Hands-on Exercise: Using a SaaS Application you will create a free account with the CRM chosen as the prototype, configure it for Hortalia, import a fictional customer base, build Jordi's shops pipeline, switch on two-step verification, query the contacts through the API, export the data as an exit plan and, when you are done, delete the test account.

© Copyright 2026. All rights reserved