Ground Truth field notes · defensive security

Home›Cloud Security›Purview & governance

Deep dive + field case · external sharing automation

Making "Specific people" links expire, per person

A team sharing case files with outside reviewers wanted every reviewer's access to end 55 days after it was granted, with nothing to type at share time. Microsoft 365 can't do that: it only expires "Anyone" links. Here's the daily flow that does it, why it has to age people rather than links, and the two traps that only showed up once it was running for real.

The ticket said "links expire after 30 days, please make it 55." It sounded like a single tenant setting. It wasn't. The 30-day limit the team was blaming had never applied to a single one of their shares, and the setting they wanted doesn't exist for the kind of link they actually use. What fixed it was a small Power Automate flow, but the useful part of this note is how we found out what to build, and the things that were only visible after go-live.

The one idea worth keeping: a sharing link is not a share date. SharePoint reuses links, so if you want access to end N days after someone was given it, you have to read each person's own invite date.

01Prove the cause before you build

The user's explanation was wrong. The tenant settings and 90 days of audit log said so in ten minutes.

Two read-only checks decided everything. First, the tenant's sharing settings (Get-SPOTenant):

SettingValueWhat it actually means
RequireAnonymousLinksExpireInDays30Anyone links expire at 30 days. Nothing else does.
ExternalUserExpirationRequiredFalseGuest access never expires; the day count next to it is ignored
DefaultSharingLinkTypeDirectShares default to Specific people
EnableAzureADB2BIntegrationFalseYet every share still created an Entra guest at share time

Then 90 days of Search-UnifiedAuditLog -RecordType SharePointSharingOperation for the people who share:

We also chased one red herring. About 4,800 files had been recycled in those 90 days, which looked like a cause. Matching shared files against deletions showed only 5 of 245 shared files deleted, all 45+ days after sharing. That was normal housekeeping. Whatever the reviewers had run into, it wasn't a tenant expiry. The real request was simpler and still valid: make access end on a known date, automatically.

02What Microsoft 365 can and can't expire

There is an admin expiry for Anyone links. There is none for Specific people links. The nearest thing expires the wrong object.

OptionWhy not (or why yes)
Raise the tenant link expiry to 55Only affects Anyone links, which this team never used. The client also wanted Anyone kept at 30.
Sharer types a date on every linkWorks, but 50+ cases a month, and one forgotten date means a reviewer with access forever
Site guest expirationExpires the guest, not the share. A reviewer on three cases loses all three at once, on a clock that started at first access. Not retroactive; every extension is a manual owner step.
Azure runbook + app registrationViable, but certificates, admin consent and app-only retesting of every SharePoint call. Kept for later.
Daily Power Automate flow, per personChosen Standard connectors only, matches the ask exactly, every removal logged

Mental model

A library where each visitor's card stops working 55 days after the librarian handed it over. The librarian never has to remember. A helper walks round every morning at six, checks every card, takes back the ones that are too old, and leaves a note for the office saying whose cards were taken back.

03Three designs, one survivor

Each version was killed by something real SharePoint did in testing.

  1. One clock per case folder. Use the folder's created date. Dead quickly: a folder is created days before it's shared, and people often share a single file, not the folder.
  2. One clock per link. Read each link's Created date, revoke links older than 55 days. Simple, and wrong. When you share a file with a second reviewer, SharePoint usually adds them to the existing link. The second reviewer inherits the first reviewer's date and loses access early. That's the 900 AddedToSecureLink events from section 01.
  3. One clock per person. Each link carries an Invitations list with every member's own invitedOn. Remove only the people past 55 days; revoke the whole link only when everyone on it has expired.
ONE LINK, TWO PEOPLE, TWO DATES review-package.pdf one Specific-people link A invitedOn Aug 1 B invitedOn Sep 10 (B was added to A's link) Per-link: link Created = Aug 1 Sep 25 → revoke the link → B cut off 40 days early Per-person: read each invitedOn Sep 25 → remove A from the link only Nov 4 → B expired too → revoke the whole link Expiry belongs to the person, not to the link.
Why the obvious design fails. SharePoint quietly reuses links when you add people, so a link's created date says nothing about when the second, third or fifth reviewer was given access.

And then there's the share that has no date at all. When the sharer types an email and clicks Send instead of Copy link, SharePoint often grants a direct permission on the item rather than a link. GetSharingInformation lists that person under principals, with no invite date anywhere. The only way to age it is to remember when you first saw it, so the flow keeps a small tracker list: item ID, person ID, first seen, last seen.

04How the flow works

One scheduled flow, five SharePoint REST calls, one report. Nothing for the sharer to do.

DAILY 06:00 · RUNS AS A SERVICE ACCOUNT Page library 5,000 at a time Shared only unique permissions Sharing info POST GetSharingInfo… Copy-link shares each person's invitedOn < cutoff? remove person · or revoke link Send (direct) shares first seen in tracker list delete role assignment RunLog → one HTML report (only if changes)
Two branches for two kinds of share. Links carry their own per-person dates; direct grants don't, so the flow writes its own. Site members are never touched; only external principals are evaluated.

Everything that touches sharing goes through Send an HTTP request to SharePoint, a standard connector action that calls the REST API as the connection's account. The normal SharePoint actions can't read link members or remove one person from a link.

PurposeCallNeeds
List items + whether each has its own permissionsGET …/items?$select=Id,FileRef,HasUniqueRoleAssignments&$top=5000Read
Links, members, invite dates, direct grantsPOST …/items(id)/GetSharingInformation?$expand=permissionsInformationSite Owner
Revoke a whole linkPOST …/items(id)/UnshareLinkSite Owner
Remove one person from a linkPOST _api/web/sitegroups/getbyname('SharingLinks.<item>.Flexible.<shareId>')/users/removebyid(id)Site Collection Admin
Remove a direct (Send) grantPOST …/roleassignments/getbyprincipalid(id) + X-HTTP-Method: DELETESite Owner

The fourth call is the one to understand. Behind every Specific-people link, SharePoint keeps a hidden group named SharingLinks.<item id>.Flexible.<link id>. The people on the link are that group's members. Remove a member and that person is off the link while it keeps working for everyone else.

Three details that each cost a test cycle:

The report is built from a RunLog array of small records (action, file, folder, person, shared date, days, who still has access), turned into table rows with a Select and wrapped in one Compose of table-based, inline-styled HTML, because Outlook desktop ignores most modern CSS. It's sent from a shared mailbox the service account has Send As on, so it reads "Expert Access Alerts" rather than a service account name, and only on days something changed. A DryRun switch makes the flow do everything except remove, with "would revoke" wording and a yellow banner, which is how every test ran.

The one-line model

When the platform has no expiry for a kind of access, don't expire the object that's easiest to see (the folder, the link, the guest). Expire the thing the requirement is actually about, here each person's grant, and read that date from where SharePoint really stores it.

05The 403 that testing hides

Everything passed under my account. Under the service account, per-person removal failed.

Site Owner can't edit the hidden SharingLinks groups

The flow was built and tested under the engineer account that created the site, and site creators are Site Collection Admins automatically. Moved to a dedicated service account with Site Owner (Full Control), the "remove one person from a link" call returned 403 Access denied. Revoking a whole link and deleting direct grants still worked, so only the partial case broke. The fix is Set-SPOUser -IsSiteCollectionAdmin $true for the service account on that one site only. If you test as the site creator, you'll never see this until production.

The service account itself is deliberately boring: no directory roles, password in the vault and set not to expire (a password change breaks every connection), MFA registered, one licence with only Exchange, SharePoint and Power Automate switched on, Site Collection Admin on one site, Send As on one mailbox, and its own mail forwarded to the alerts DL because flow-failure notices go to owners. One gotcha: assigning the licence seconds after creating the account left the Exchange plan in Error for a while, because Exchange couldn't see the user yet. Wait a minute or two before licensing.

06Day one: the 5,000-item wall

The first scheduled run succeeded. It had also only looked at two-thirds of the library.

The morning after go-live the flow ran green. Its first REST call had returned exactly 5,000 items, all from a single case, with an odata.nextLink at the top of the reply. The library held 7,528. The team's first case included imaging discs: a DICOM viewer is thousands of small files, and one case had pushed the library past 5,000 within hours.

SharePoint returns at most 5,000 items per REST request and hands you the address of the next page. A flow that makes one call never sees the rest. When we fixed it, page two held all four of the team's first real reviewer shares. Without the fix, none of them would ever have expired, and nothing would have looked wrong.

The fix is a Do until loop that follows odata.nextLink until it's empty, filtering each page down to shared items as it goes so the working set stays small:

NextUrl     = _api/web/lists/getbytitle('Documents')/items?$select=Id,FileRef,FileDirRef,HasUniqueRoleAssignments&$top=5000
Do until    = empty(variables('NextUrl'))
  Get page  = GET @{variables('NextUrl')}
  Merged    = union(variables('SharedItems'), body('Page_shared'))
  NextUrl   = if(empty(body('Get_page')?['odata.nextLink']), '',
                substring(body('Get_page')?['odata.nextLink'],
                          indexOf(body('Get_page')?['odata.nextLink'], '_api/')))

Two small things in there: Set variable can't reference itself, hence the Merged Compose, and the next-page address comes back absolute, so it's cut back to _api/… to match the relative form the SharePoint action expects. Verified on the next run: two pages, 5,000 + 2,528, matching the item count in Site contents, and all four shares found.

Myth

A green run means the flow checked everything.

Reality

A capped REST reply is a success. Compare what the flow read against the library count in Site contents after the first real day of use, not just after testing on an empty site.

Myth

Site Owner is enough to manage sharing on a site.

Reality

Owners can revoke whole links, but removing one person from a link edits a system-owned group and needs Site Collection Admin.

07Testing without waiting 55 days

You can't backdate a sharing link. You can move the line instead.

TechniqueSet the cutoff toUse it for
Short cutoffaddMinutes(utcNow(), -2)Anything shared more than two minutes ago counts as expired
Pinned cutoffA fixed UTC time between two sharesPer-person tests: the earlier reviewer expires, the later one doesn't, however long you take
Backdate the trackerLeave it at N days; edit FirstSeenSend shares at the real production setting
Dry runDryRun = trueEverything except the removal, with "would" wording

Every path was run dry then live: link one and two folders deep, two reviewers on one link with both expired and with one expired, a direct Send share, placeholder links, and site members checked after every removal. Remember the timezone: SharePoint stores UTC, so a pinned cutoff typed in local time is hours off.

08The setup scripts

The flow is built by hand in the designer. Everything around it is scripted, interactive and reusable.

FileWhat it doesChanges anything?
01-Get-SharingBaseline.ps1Tenant sharing settings + audit-log summary: Anyone vs Specific-people links, people added to existing links, manual expiry datesNo
02-New-AutomationServiceAccount.ps1Role-less account, password shown once, licence with only the plans you keep, waits for Exchange firstYes
03-Set-ShareExpirySite.ps1Anyone links off on the site, Specific people default, guest expiry override off, service account Owner + Site Collection AdminYes
04-New-AlertSenderMailbox.ps1Hidden shared sender mailbox, Send As, service account mail forwarded to the alerts DLYes

01 and 03 need Windows PowerShell 5.1: the SharePoint Online cmdlets aren't recognised in PowerShell 7. The download also includes the report's HTML template.

⇩  Download the toolkit — 4 scripts + email template (.zip)

09Limits worth stating up front

Sources & further reading

Comments

Questions or corrections welcome. Sign in with GitHub to join the thread.