Skip to content

Commit fc860ac

Browse files
Provision staff accounts from Entra ID and Okta over SCIM 2.0 (#992)
1 parent 89bae1a commit fc860ac

50 files changed

Lines changed: 4688 additions & 1 deletion

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎GrandNode.slnx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
<Project Path="src/Modules/Grand.Module.Installer/Grand.Module.Installer.csproj" />
3434
<Project Path="src/Modules/Grand.Module.Migration/Grand.Module.Migration.csproj" />
3535
<Project Path="src/Modules/Grand.Module.ScheduledTasks/Grand.Module.ScheduledTasks.csproj" />
36+
<Project Path="src/Modules/Grand.Module.Scim/Grand.Module.Scim.csproj" />
3637
</Folder>
3738
<Folder Name="/Plugins/">
3839
<Project Path="src/Plugins/Authentication.Facebook/Authentication.Facebook.csproj" />

‎docs/scim.md‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
# SCIM 2.0 provisioning of staff accounts
2+
3+
How to let Microsoft Entra ID or Okta create, update and lock out the GrandNode accounts of your employees, and give
4+
them their GrandNode roles from the identity provider's groups.
5+
6+
## 1. What it does
7+
8+
GrandNode is a SCIM 2.0 **service provider** (RFC 7643, RFC 7644) at `/scim/v2`. The identity provider that already signs
9+
your staff in through OpenID Connect ([docs/oidc-resource-server.md](oidc-resource-server.md), sections 11 and 12) pushes:
10+
11+
* **Users.** A new employee gets an account before the first sign-in. Name and e-mail follow the identity provider.
12+
Deactivating or deleting the user at the provider locks the account out at once (section 4).
13+
* **Groups.** A group grants nothing until an administrator maps it to a customer group in
14+
**Admin > Configuration > External authentication > SCIM provisioning**. From then on, membership of the group gives
15+
the role and leaving the group takes it away.
16+
17+
What it is not:
18+
19+
* Not for storefront customers, not for B2B customer companies, and not for more than one identity provider. It
20+
provisions the employees of the company that runs the store, through the one provider of `OidcResourceServer`.
21+
* No SAML. Sign-in stays OpenID Connect.
22+
* No `/Bulk`, `/Me`, sorting, ETags, `/.search` or password changes. The discovery documents say so.
23+
24+
## 2. Configuration
25+
26+
1. Configure and test the OpenID Connect sign-in first (`OidcResourceServer` and `OidcLogin`). Without it every SCIM
27+
request is refused. On a fresh installation also switch the method on in **Admin > Configuration > External
28+
authentication** (`ExternalAuth.OpenIdConnect`): until then the sign-in button fails, and provisioned staff cannot sign
29+
in.
30+
2. Turn the module on: `FeatureManagement:Grand.Module.Scim = true`. The module is built with the solution
31+
(`src/Modules/Grand.Module.Scim`).
32+
3. Set section `Scim`:
33+
34+
| Key | Default | Meaning |
35+
|---|---|---|
36+
| `Token` | empty | The Bearer token the identity provider sends. At least 32 characters; shorter means every request is refused. Keep it out of source control (`Scim__Token` or a secret store). Generate it, for example, with `openssl rand -base64 48`. |
37+
| `ExternalIdIsSubject` | `true` | The SCIM `externalId` of a user is its OpenID Connect subject. An account SCIM **creates** is linked to it, so its first sign-in needs no password. A taken-over account is not (section 4). See section 3. |
38+
| `TakeOverDomains` | `[]` | E-mail domains of the company, e.g. `["firma.pl"]`. An existing shopper account with such an e-mail (an employee's shopping account) is taken over like a staff account. Exact domains only, no subdomains. See section 4. |
39+
| `MaxResults` | `100` | Largest page of a list response. |
40+
41+
4. Put your own administrator e-mail in `OidcLogin:BreakGlassAccounts`. SCIM never touches a break-glass account. Every
42+
other staff account that SCIM takes over loses its back-office roles until its groups are mapped (section 5), and that
43+
includes yours.
44+
5. Restart, open **SCIM provisioning** in the admin panel, and copy the **SCIM endpoint (tenant URL)**. Push the groups and
45+
map them before you assign users, so the first cycle does not demote the staff it takes over.
46+
47+
## 3. Identity providers
48+
49+
### 3.1 Microsoft Entra ID
50+
51+
* Enterprise application of GrandNode > **Provisioning** > Automatic. Tenant URL: the endpoint from the admin screen;
52+
Secret token: `Scim:Token`. **Test connection** must pass (it filters for a random `userName` and expects an empty list).
53+
* **Attribute mapping (users):** map `objectId` → `externalId`. Entra's default maps `mailNickname` there, which is not the
54+
OpenID Connect identity.
55+
* **OpenID Connect:** set `OidcResourceServer:Claims:Subject = "oid"`. Entra's `sub` is different for every application and
56+
never equals the object id. The `oid` claim comes with the `profile` scope, which `OidcLogin:Scopes` requests by default.
57+
On an installation whose staff already sign in through Entra, the links stored so far hold the old `sub`. After the change
58+
no stored link matches any more. Remove them (**External authentication > OpenID Connect account links > Remove**) and
59+
let everybody connect again.
60+
* `userName` is the account's e-mail. Entra sends the UPN. If your UPNs are not mailboxes, map `userName` to `mail`.
61+
* Groups: assign the groups to the application. Entra reads them with `excludedAttributes=members`, and GrandNode
62+
supports that.
63+
64+
### 3.2 Okta
65+
66+
* SCIM 2.0 app integration > **Provisioning** > Integration. SCIM connector base URL: the endpoint. Unique identifier field:
67+
`userName`. Authentication mode: HTTP Header with the token. Enable Create, Update and Deactivate users, and Push Groups.
68+
* Okta fills its own `externalId` with the id GrandNode returns and does not send its user id by default. Choose one:
69+
* map the SCIM `externalId` to the Okta user id (Profile Editor of the app, expression `user.getInternalProperty("id")`).
70+
The Okta user id is Okta's OpenID Connect `sub`, so keep `ExternalIdIsSubject = true`. Check in your tenant that the
71+
attribute is sent;
72+
* or set `Scim:ExternalIdIsSubject = false` and `OidcLogin:SignInMode = ProviderOnly`, so an account is linked at its first
73+
sign-in by its provider-verified e-mail. In `Mixed` mode a staff account links only with its password, and a SCIM
74+
account has none anybody knows. GrandNode logs a warning at startup for that combination.
75+
76+
## 4. Behaviour
77+
78+
**Create.** No account with the e-mail: a registered, active account is created and linked to the user's OpenID Connect
79+
subject. Without a mapped back-office group it is an ordinary customer account, and the employee shops with it. Map a group to
80+
a custom customer group (e.g. "Employees") for employee prices or discounts. It belongs to no store, so with per-store identity it is usable on every store host. Its password is random and
81+
nobody knows it, and no welcome e-mail is sent.
82+
83+
A **staff** account (admin panel access, a staff store or a vendor) with the e-mail already exists, or a **shopper** account
84+
whose e-mail is in `Scim:TakeOverDomains`: **SCIM takes it over** and manages its roles from then on (section 5). An
85+
employee's shopping account keeps its orders and addresses, and is deactivated when the employee leaves. It is **not** linked ahead. An e-mail at the identity provider proves nothing about
86+
who owns the GrandNode account, so the employee connects once at the first sign-in with the account's password (and second
87+
factor), exactly as without SCIM.
88+
89+
A shopper account **loses its credentials** when SCIM takes it over: GrandNode never verified who registered the address, and
90+
the roles the identity provider gives must not reach a stranger's password. Its password becomes one nobody knows, its
91+
sessions, Frontend API refresh token and second factor are dropped, and its external sign-ins other than OpenID Connect
92+
(Facebook, Google...) are removed. The employee sets a new password through password recovery (the e-mail goes to the
93+
company mailbox) and then connects. A staff account keeps its credentials: an administrator created it.
94+
95+
Refused with `409 uniqueness`:
96+
* a shopper account whose e-mail is not in `Scim:TakeOverDomains`. Without this rule, a user admin at the identity provider
97+
could lock out, or give roles to, any storefront customer;
98+
* system accounts, deleted accounts and break-glass addresses (`OidcLogin:BreakGlassAccounts`), also one without an account yet;
99+
* a store-bound account with per-store identity;
100+
* an account linked to another OpenID Connect identity;
101+
* a second user with the same `externalId`.
102+
103+
**Update.** E-mail (and a user name that was the e-mail), first and last name. Refused with `409`, with nothing written:
104+
* a new e-mail that belongs to another account, or a break-glass address;
105+
* an `externalId` another user has.
106+
107+
**Deactivate** (`active: false`). The account becomes inactive, which the cookie, Frontend API and Backend API checks refuse on
108+
the next request. Its OpenID Connect sessions end, the provider access tokens of its subject issued so far are refused, and
109+
its Frontend API refresh token is dropped, and its password token changes, so cookies issued before stay invalid after a
110+
reactivation.
111+
112+
**Reactivate** (`active: true`). Only an account SCIM deactivated. An account an administrator disabled by hand stays disabled,
113+
and SCIM reports it as inactive.
114+
115+
**Delete.** The account is deactivated, loses every role SCIM granted and its OpenID Connect link, and leaves every group. The
116+
customer itself is kept with its orders and history, and SCIM no longer shows it. When the provider creates the same user
117+
again, it gets the same account back, active again if SCIM had deactivated it. A break-glass account is refused with `409`.
118+
A customer deleted in the admin panel leaves SCIM entirely. The provider can then create the user again as a new account.
119+
120+
**Unknown attributes** of a user (title, department, phone numbers...) are accepted and ignored.
121+
122+
## 5. Roles
123+
124+
Map each group on the admin screen to one of:
125+
126+
| Customer group | Also needs | Members get |
127+
|---|---|---|
128+
| Administrators | - | the Admin panel |
129+
| Store managers | a store | the Store panel of that store (`StaffStoreId`) |
130+
| Vendors | a vendor | the Vendor panel of that vendor (`VendorId`) |
131+
| a custom (non-system) group | - | that group |
132+
133+
Sales managers cannot be mapped, because they need a sales employee. Only an administrator can map a group to
134+
Administrators, or change a group mapped to it. Group display names may repeat, as in Entra.
135+
136+
* **Break-glass accounts** keep their roles whatever their groups say.
137+
* **Granted by SCIM only.** SCIM remembers what it granted and takes away only that. Groups an administrator assigned by hand
138+
stay. Removing or changing a mapping takes its role away from every member at once.
139+
* **Takeover.** When SCIM takes over an existing account, its Administrators / Store managers / Vendors roles, its store and
140+
vendor, and every mapped group it holds count as granted by SCIM. An employee who is in no mapped group loses them
141+
immediately, which is what "managed by SCIM" means.
142+
* **Conflicts.** The back-office roles must be one of: Administrators alone, Store managers with one store, Vendors with one
143+
vendor. If a user's groups give anything else (Administrators and Store managers, two stores, Vendors and Store managers),
144+
SCIM grants **none** of these roles, still grants the custom groups, and lists the account under **Role conflicts** on the
145+
admin screen.
146+
147+
## 6. Security
148+
149+
* Only the Bearer token of `Scim:Token` is accepted, compared in constant time. Discovery endpoints need it too. Rotate it
150+
at the provider and in appsettings together.
151+
* The endpoint is refused entirely while the token is shorter than 32 characters or the OpenID Connect sign-in is not
152+
configured. Startup logs an error in that case.
153+
* Logs carry customer ids, never e-mails or tokens.
154+
* Request bodies are limited to 1 MB.
155+
156+
## 7. Endpoints
157+
158+
| Method | Path | Notes |
159+
|---|---|---|
160+
| GET | `/scim/v2/Users` | `filter=userName eq "..."` or `externalId eq "..."`, `startIndex`, `count` |
161+
| GET, PUT, PATCH, DELETE | `/scim/v2/Users/{id}` | `id` is the customer id. PUT without `active` keeps the current state |
162+
| POST | `/scim/v2/Users` | `201` with `Location` |
163+
| GET | `/scim/v2/Groups` | `filter=displayName eq "..."` or `externalId eq "..."`, `excludedAttributes=members` |
164+
| GET, PUT, PATCH, DELETE | `/scim/v2/Groups/{id}` | PATCH: `members` add/remove/replace, `members[value eq "id"]` remove, rename |
165+
| POST | `/scim/v2/Groups` | members that are not SCIM-managed users are ignored |
166+
| GET | `/scim/v2/ServiceProviderConfig`, `/ResourceTypes`, `/Schemas` | discovery |
167+
168+
Errors use the SCIM error schema: `400 invalidFilter` / `invalidValue` / `invalidSyntax`, `401`, `404`, `409 uniqueness`.
169+
170+
## 8. Storage
171+
172+
Two collections, created on first use (no migration):
173+
174+
* `ScimUser`: one document per managed account, its id **is** the customer id. It holds the `externalId`, what SCIM granted,
175+
whether SCIM created the account, and whether the provider deleted the user.
176+
* `ScimGroup`: the groups received and their mapping.
177+
178+
Turning the module off stops provisioning. Accounts, roles and the stored records stay as they are.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using Grand.Data;
2+
using Grand.Domain.Customers;
3+
using Grand.Infrastructure.Events;
4+
using Grand.Mediator;
5+
6+
namespace Grand.Business.Authentication.Events;
7+
8+
/// <summary>
9+
/// A customer deleted in the admin panel leaves SCIM: its record and its group memberships go, so the identity provider can
10+
/// provision the user again as a new account
11+
/// </summary>
12+
public class ScimCustomerDeletedEventHandler(IRepository<ScimUser> users, IRepository<ScimGroup> groups)
13+
: INotificationHandler<EntityDeleted<Customer>>
14+
{
15+
public async Task Handle(EntityDeleted<Customer> notification, CancellationToken cancellationToken)
16+
{
17+
var customerId = notification.Entity.Id;
18+
var record = await users.GetByIdAsync(customerId);
19+
if (record != null)
20+
await users.DeleteAsync(record);
21+
22+
foreach (var group in await groups.ToListAsync(groups.Table.Where(x => x.Members.Contains(customerId)),
23+
cancellationToken))
24+
await groups.RemoveCollectionFieldItem(group.Id, x => x.Members, m => m == customerId);
25+
}
26+
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
using Grand.Business.Core.Interfaces.Authentication;
2+
using Grand.Business.Core.Interfaces.Customers;
3+
using Grand.Business.Core.Utilities.Customers;
4+
using Grand.Data;
5+
using Grand.Domain.Customers;
6+
using Microsoft.Extensions.Logging;
7+
using System.Security.Cryptography;
8+
9+
namespace Grand.Business.Authentication.Services.Scim;
10+
11+
/// <summary>
12+
/// Locks a SCIM-managed account out at once: inactive (refused by the cookie, Frontend API and Backend API checks on the next
13+
/// request), its provider sessions ended, the provider access tokens of its subject refused, its Frontend API refresh
14+
/// token dropped and its password token rotated (cookies issued before do not come back with a reactivation)
15+
/// </summary>
16+
public class ScimAccountLock(
17+
ICustomerService customerService,
18+
ICustomerManagerService customerManagerService,
19+
IRepository<ExternalAuthentication> links,
20+
IOidcSessionService sessionService,
21+
IOidcTokenRevocationService tokenRevocationService,
22+
ILogger<ScimAccountLock> logger)
23+
{
24+
public virtual async Task Deactivate(Customer customer)
25+
{
26+
ArgumentNullException.ThrowIfNull(customer);
27+
28+
await customerService.UpdateCustomerField(customer.Id, x => x.Active, false);
29+
customer.Active = false;
30+
await sessionService.EndByCustomer(customer.Id);
31+
32+
var link = await links.GetOneAsync(x =>
33+
x.ProviderSystemName == OidcCustomerResolver.ProviderSystemName && x.CustomerId == customer.Id);
34+
if (link != null)
35+
await tokenRevocationService.RevokeTokens(link.ExternalIdentifier);
36+
37+
//an empty value removes the user field
38+
await customerService.UpdateUserField(customer, SystemCustomerFieldNames.RefreshToken, "");
39+
//a new password token invalidates the cookies issued so far, so they stay dead after a reactivation
40+
await customerService.UpdateUserField(customer, SystemCustomerFieldNames.PasswordToken, Guid.NewGuid().ToString());
41+
logger.LogInformation("SCIM deactivated customer {CustomerId}", customer.Id);
42+
}
43+
44+
/// <summary>
45+
/// Leaves a shopper account SCIM takes over to the owner of its mailbox: whoever registered it (an e-mail nobody verified)
46+
/// must not get the roles the identity provider gives. The password becomes one nobody knows (a new password token ends
47+
/// the cookies), the sessions, the Frontend API refresh token, the second factor and the external sign-ins other than
48+
/// OpenID Connect go. The employee sets a password through password recovery and connects at the first sign-in
49+
/// </summary>
50+
public virtual async Task ResetCredentials(Customer customer)
51+
{
52+
ArgumentNullException.ThrowIfNull(customer);
53+
54+
await sessionService.EndByCustomer(customer.Id);
55+
await links.DeleteManyAsync(x =>
56+
x.CustomerId == customer.Id && x.ProviderSystemName != OidcCustomerResolver.ProviderSystemName);
57+
58+
//an empty value removes the user field
59+
await customerService.UpdateUserField(customer, SystemCustomerFieldNames.RefreshToken, "");
60+
await customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFactorEnabled, "");
61+
await customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFactorSecretKey, "");
62+
63+
//also writes a new password token
64+
var password = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
65+
await customerManagerService.ChangePassword(new ChangePasswordRequest(customer.Email, PasswordFormat.Hashed, password));
66+
logger.LogInformation("SCIM reset the credentials of customer {CustomerId}", customer.Id);
67+
}
68+
69+
public virtual async Task Activate(Customer customer)
70+
{
71+
ArgumentNullException.ThrowIfNull(customer);
72+
73+
await customerService.UpdateCustomerField(customer.Id, x => x.Active, true);
74+
customer.Active = true;
75+
logger.LogInformation("SCIM activated customer {CustomerId}", customer.Id);
76+
}
77+
}

0 commit comments

Comments
 (0)