Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Add support for OIDC-claim based automatic role mapping.

Kailash Nadh7f907aab19eb
diff --git a/cmd/auth.go b/cmd/auth.go
index a4091926..910e468b 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -10,6 +10,7 @@ import (
"net/http"
"net/mail"
"net/url"
+ "slices"
"strings"
"time"
@@ -426,9 +427,16 @@ func (a *App) createOIDCUser(claims auth.OIDCclaim, c echo.Context) (auth.User,
name = strings.Split(claims.Email, "@")[0]
}
+ userRoleID, claimListRoleID := resolveOIDCRoles(
+ claims.RawClaims,
+ a.cfg.Security.OIDC.Roles,
+ a.cfg.Security.OIDC.DefaultUserRoleID,
+ a.cfg.Security.OIDC.DefaultListRoleID,
+ )
+
var listRoleID *int
- if a.cfg.Security.OIDC.DefaultListRoleID > 0 {
- listRoleID = &a.cfg.Security.OIDC.DefaultListRoleID
+ if claimListRoleID > 0 {
+ listRoleID = &claimListRoleID
}
user, err := a.core.CreateUser(auth.User{
@@ -438,7 +446,7 @@ func (a *App) createOIDCUser(claims auth.OIDCclaim, c echo.Context) (auth.User,
Username: claims.Email,
Name: name,
Email: null.NewString(claims.Email, true),
- UserRoleID: a.cfg.Security.OIDC.DefaultUserRoleID,
+ UserRoleID: userRoleID,
ListRoleID: listRoleID,
Status: auth.UserStatusEnabled,
})
@@ -792,3 +800,87 @@ func (a *App) GenerateTOTPQR(c echo.Context) error {
QR: base64.StdEncoding.EncodeToString(buf.Bytes()),
}})
}
+
+// resolveOIDCRoles applies the first matching mapping, retaining defaults for omitted roles.
+func resolveOIDCRoles(claims map[string]json.RawMessage, roles []models.OIDCRoleMapping, userRoleID, listRoleID int) (int, int) {
+ for _, m := range roles {
+ if !oidcClaimMatches(claims[m.Claim], m.Match) {
+ continue
+ }
+
+ if m.UserRoleID != nil {
+ userRoleID = *m.UserRoleID
+ }
+
+ if m.ListRoleID != nil {
+ listRoleID = *m.ListRoleID
+ }
+
+ break
+ }
+
+ return userRoleID, listRoleID
+}
+
+// oidcClaimMatches accepts only strings and arrays containing exclusively strings.
+func oidcClaimMatches(raw json.RawMessage, expected string) bool {
+ var claim any
+ if err := json.Unmarshal(raw, &claim); err != nil {
+ return false
+ }
+
+ switch v := claim.(type) {
+ case string:
+ return v == expected
+ case []any:
+ matched := false
+ for _, item := range v {
+ s, ok := item.(string)
+ if !ok {
+ return false
+ }
+ matched = matched || s == expected
+ }
+
+ return matched
+ }
+
+ return false
+}
+
+// validateOIDCRoles checks mapping fields and references to each role type.
+func validateOIDCRoles(roles []models.OIDCRoleMapping, userRoles []auth.Role, listRoles []auth.ListRole) error {
+ for i, m := range roles {
+ var msg string
+ switch {
+ case m.Claim == "":
+ msg = "claim is required"
+ case m.Match == "":
+ msg = "match is required"
+ case m.UserRoleID != nil && !slices.ContainsFunc(userRoles, func(r auth.Role) bool { return r.ID == *m.UserRoleID }):
+ msg = fmt.Sprintf("user role ID %d does not exist", *m.UserRoleID)
+ case m.ListRoleID != nil && !slices.ContainsFunc(listRoles, func(r auth.ListRole) bool { return r.ID == *m.ListRoleID }):
+ msg = fmt.Sprintf("list role ID %d does not exist", *m.ListRoleID)
+ }
+
+ if msg != "" {
+ return fmt.Errorf("OIDC role mapping %d: %s", i+1, msg)
+ }
+ }
+
+ return nil
+}
+
+// validateOIDCSettings checks defaults even when automatic user creation is disabled.
+func validateOIDCSettings(set models.Settings, userRoles []auth.Role, listRoles []auth.ListRole) error {
+ o := set.OIDC
+ if o.AutoCreateUsers || o.DefaultUserRoleID.Valid {
+ if !o.DefaultUserRoleID.Valid || !slices.ContainsFunc(userRoles, func(r auth.Role) bool { return r.ID == o.DefaultUserRoleID.Int }) {
+ return fmt.Errorf("OIDC default user role ID %d does not exist", o.DefaultUserRoleID.Int)
+ }
+ }
+ if o.DefaultListRoleID.Valid && !slices.ContainsFunc(listRoles, func(r auth.ListRole) bool { return r.ID == o.DefaultListRoleID.Int }) {
+ return fmt.Errorf("OIDC default list role ID %d does not exist", o.DefaultListRoleID.Int)
+ }
+ return validateOIDCRoles(o.Roles, userRoles, listRoles)
+}
diff --git a/cmd/init.go b/cmd/init.go
index e9f125cc..25877567 100644
--- a/cmd/init.go
+++ b/cmd/init.go
@@ -110,14 +110,15 @@ type Config struct {
} `koanf:"privacy"`
Security struct {
OIDC struct {
- Enabled bool `koanf:"enabled"`
- ProviderURL string `koanf:"provider_url"`
- ProviderName string `koanf:"provider_name"`
- ClientID string `koanf:"client_id"`
- ClientSecret string `koanf:"client_secret"`
- AutoCreateUsers bool `koanf:"auto_create_users"`
- DefaultUserRoleID int `koanf:"default_user_role_id"`
- DefaultListRoleID int `koanf:"default_list_role_id"`
+ Enabled bool `koanf:"enabled"`
+ ProviderURL string `koanf:"provider_url"`
+ ProviderName string `koanf:"provider_name"`
+ ClientID string `koanf:"client_id"`
+ ClientSecret string `koanf:"client_secret"`
+ AutoCreateUsers bool `koanf:"auto_create_users"`
+ DefaultUserRoleID int `koanf:"default_user_role_id"`
+ DefaultListRoleID int `koanf:"default_list_role_id"`
+ Roles []models.OIDCRoleMapping `koanf:"roles"`
} `koanf:"oidc"`
Captcha struct {
diff --git a/cmd/settings.go b/cmd/settings.go
index 00fa9b58..fb50ccf8 100644
--- a/cmd/settings.go
+++ b/cmd/settings.go
@@ -161,6 +161,12 @@ func (a *App) UpdateSettings(c echo.Context) error {
return err
}
+ // Preserve the OIDC role mapping when older clients do not send the field.
+ // An explicit empty array still clears the mapping.
+ if set.OIDC.Roles == nil {
+ set.OIDC.Roles = cur.OIDC.Roles
+ }
+
// Validate and sanitize postback Messenger names along with SMTP names
// (where each SMTP is also considered as a standalone messenger).
// Duplicates are disallowed and "email" is a reserved name.
@@ -321,10 +327,14 @@ func (a *App) UpdateSettings(c echo.Context) error {
if set.OIDC.AutoCreateUsers {
if set.OIDC.DefaultUserRoleID.Int < auth.SuperAdminRoleID {
return echo.NewHTTPError(http.StatusBadRequest,
- a.i18n.Ts("globals.messages.invalidFields", "name", a.i18n.T("settings.security.OIDCDefaultRole")))
+ a.i18n.Ts("globals.messages.invalidFields", "name", a.i18n.T("settings.security.OIDCDefaultUserRole")))
}
}
+ if err := a.validateOIDCRoles(set.OIDC.Roles); err != nil {
+ return err
+ }
+
for n, v := range set.UploadExtensions {
set.UploadExtensions[n] = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(v), "."))
}
@@ -394,6 +404,18 @@ func (a *App) UpdateSettingsByKey(c echo.Context) error {
return err
}
+ // The raw settings endpoint must validate role mapping too.
+ if key == "security.oidc" {
+ var set models.Settings
+ if err := json.Unmarshal(b, &set.OIDC); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("globals.messages.invalidData"))
+ }
+
+ if err := a.validateOIDCRoles(set.OIDC.Roles); err != nil {
+ return err
+ }
+ }
+
// Update the value in the DB.
if err := a.core.UpdateSettingsByKey(key, b); err != nil {
return err
@@ -402,6 +424,25 @@ func (a *App) UpdateSettingsByKey(c echo.Context) error {
return a.handleSettingsRestart(c)
}
+// validateOIDCRoles loads roles only when the mapping needs validation.
+func (a *App) validateOIDCRoles(roles []models.OIDCRoleMapping) error {
+ if len(roles) == 0 {
+ return nil
+ }
+ userRoles, err := a.core.GetRoles("", "", "")
+ if err != nil {
+ return err
+ }
+ listRoles, err := a.core.GetListRoles("", "", "")
+ if err != nil {
+ return err
+ }
+ if err := validateOIDCRoles(roles, userRoles, listRoles); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, err.Error())
+ }
+ return nil
+}
+
// handleSettingsRestart checks for running campaigns and either triggers an
// immediate app restart or marks the app as needing a restart.
func (a *App) handleSettingsRestart(c echo.Context) error {
diff --git a/cmd/upgrade.go b/cmd/upgrade.go
index 4e75515d..08ff8971 100644
--- a/cmd/upgrade.go
+++ b/cmd/upgrade.go
@@ -45,6 +45,7 @@ var migList = []migFunc{
{"v6.0.0", migrations.V6_0_0},
{"v6.1.0", migrations.V6_1_0},
{"v6.2.0", migrations.V6_2_0},
+ {"v7.0.0", migrations.V7_0_0},
}
// upgrade upgrades the database to the current version by running SQL migration files
diff --git a/docs/docs/content/oidc.md b/docs/docs/content/oidc.md
index 73f358a8..5e6ee0b5 100644
--- a/docs/docs/content/oidc.md
+++ b/docs/docs/content/oidc.md
@@ -6,6 +6,38 @@ Listmonk supports single sign-on with OIDC (OpenID Connect). Any standards compl
### User auto-creation
If `Settings -> Security -> OIDC -> Auto-create users` is turned on, when users login via OIDC, an account is auto-created if an existing account is not found (based on the OIDC e-mail ID).
+### OIDC role mapping
+
+Auto-created users can receive user and list roles based on top-level claims in the
+verified OIDC ID token. Roles are assigned only when the user is created; subsequent
+logins do not change an existing user's roles. Claims from the UserInfo endpoint
+are not used for role mapping.
+
+Configure mappings under `Settings -> Security -> OIDC -> Role mapping`, or set
+the `roles` array in `security.oidc` using the settings API. For example:
+
+```json
+"roles": [
+ {"claim": "groups", "match": "editors", "user_role_id": 2, "list_role_id": 3},
+ {"claim": "department", "match": "marketing", "user_role_id": 4}
+]
+```
+
+Replace the example role IDs with existing user and list role IDs. Each mapping
+requires a non-empty `claim` and `match`; both role IDs are optional. A claim must be
+a string equal to `match`, or an array containing only strings with at least one
+equal to `match`. Matching is exact and case-sensitive; nested claim paths are not
+supported.
+
+Mappings are evaluated in order and the first match wins. Omitted role IDs retain
+their configured defaults. If no mapping matches, both defaults apply. A default
+user role is still required when auto-creation is enabled.
+
+`PUT /api/settings` preserves mappings when `roles` is omitted or `null`; send
+`"roles": []` to clear them. `PUT /api/settings/security.oidc` replaces the entire
+OIDC configuration, so include all its settings, including the client secret and
+any mappings to retain. Both endpoints validate mapping role IDs.
+
# Tutorials
Tutorials for configuring listmonk SSO with popular OIDC providers.
@@ -113,4 +145,4 @@ In listmonk Admin → Settings → Security → OIDC:
- **Client ID**: Client ID copied from Console (e.g., `XXXX.apps.googleusercontent.com`)
- **Client Secret**: Client Secret copied from Console
- **Auto-create users from SSO**: (Optional) Enable to automatically create users who don't exist
-- **Default user role**: (Required if auto-create enabled) Select role for new users
\ No newline at end of file
+- **Default user role**: (Required if auto-create enabled) Select role for new users
diff --git a/i18n/en.json b/i18n/en.json
index 805c48fa..b174efab 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -312,6 +312,7 @@
"globals.terms.campaigns": "Campaigns",
"globals.terms.dashboard": "Dashboard",
"globals.terms.day": "Day | Days",
+ "globals.terms.default": "Default",
"globals.terms.hour": "Hour | Hours",
"globals.terms.list": "List | Lists",
"globals.terms.lists": "Lists",
@@ -337,6 +338,7 @@
"globals.terms.tx": "Transactional | Transactional",
"globals.terms.user": "User | Users",
"globals.terms.users": "Users",
+ "globals.terms.value": "Value",
"globals.terms.year": "Year | Years",
"globals.terms.import": "Import",
"globals.terms.url": "URL",
@@ -646,6 +648,9 @@
"settings.security.OIDCDefaultUserRole": "Default user role",
"settings.security.OIDCDefaultListRole": "Default list role",
"settings.security.OIDCDefaultRoleHelp": "Default role assigned to users auto-created from OIDC.",
+ "settings.security.OIDCRoleMapping": "Claim based role mapping",
+ "settings.security.OIDCRoleMappingHelp": "Applied to users on first login only. If the claim value does not match, default roles above are assigned.",
+ "settings.security.OIDCClaim": "Claim",
"settings.security.altchaComplexity": "Altcha Complexity",
"settings.security.altchaComplexityHelp": "Higher values provide better security but slower solving (1000-1000000).",
"settings.security.captchaKey": "hCaptcha.com SiteKey",
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
index 87db1a8a..c87d34d8 100644
--- a/internal/auth/auth.go
+++ b/internal/auth/auth.go
@@ -7,6 +7,7 @@ import (
"database/sql"
"encoding/base64"
"encoding/hex"
+ "encoding/json"
"errors"
"fmt"
"log"
@@ -23,12 +24,13 @@ import (
)
type OIDCclaim struct {
- Email string `json:"email"`
- EmailVerified bool `json:"email_verified"`
- Sub string `json:"sub"`
- Picture string `json:"picture"`
- Name string `json:"name"`
- PreferredUsername string `json:"preferred_username"`
+ Email string `json:"email"`
+ EmailVerified bool `json:"email_verified"`
+ Sub string `json:"sub"`
+ Picture string `json:"picture"`
+ Name string `json:"name"`
+ PreferredUsername string `json:"preferred_username"`
+ RawClaims map[string]json.RawMessage `json:"-"`
}
type OIDCConfig struct {
@@ -260,6 +262,11 @@ func (o *Auth) ExchangeOIDCToken(code, nonce string) (string, OIDCclaim, error)
return "", OIDCclaim{}, errors.New("error getting user from OIDC")
}
+ // Preserve verified ID token claims for role mapping. UserInfo must not replace these.
+ if err := idTk.Claims(&claims.RawClaims); err != nil {
+ return "", OIDCclaim{}, errors.New("error getting raw claims from OIDC")
+ }
+
// If claims doesn't have the e-mail, attempt to fetch it from the userinfo endpoint.
if claims.Email == "" {
provider, err := o.getProvider()
diff --git a/internal/migrations/v7.0.0.go b/internal/migrations/v7.0.0.go
new file mode 100644
index 00000000..36d7f772
--- /dev/null
+++ b/internal/migrations/v7.0.0.go
@@ -0,0 +1,18 @@
+package migrations
+
+import (
+ "log"
+
+ "github.com/jmoiron/sqlx"
+ "github.com/knadh/koanf/v2"
+ "github.com/knadh/stuffbin"
+)
+
+func V7_0_0(db *sqlx.DB, fs stuffbin.FileSystem, ko *koanf.Koanf, lo *log.Logger) error {
+ // OIDC claim mapping.
+ if _, err := db.Exec(`UPDATE settings SET value = JSONB_SET(value, '{roles}', '[]'::JSONB) WHERE key = 'security.oidc' AND NOT (value ? 'roles');`); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/models/settings.go b/models/settings.go
index 33a27327..84550b86 100644
--- a/models/settings.go
+++ b/models/settings.go
@@ -2,6 +2,15 @@ package models
import "gopkg.in/volatiletech/null.v6"
+// OIDCRoleMapping maps an exact OIDC claim value to the roles assigned
+// when an OIDC user is automatically created.
+type OIDCRoleMapping struct {
+ Claim string `json:"claim" koanf:"claim"`
+ Match string `json:"match" koanf:"match"`
+ UserRoleID *int `json:"user_role_id,omitempty" koanf:"user_role_id"`
+ ListRoleID *int `json:"list_role_id,omitempty" koanf:"list_role_id"`
+}
+
// Settings represents the app settings stored in the DB.
type Settings struct {
AppSiteName string `json:"app.site_name"`
@@ -54,14 +63,15 @@ type Settings struct {
} `json:"security.captcha"`
OIDC struct {
- Enabled bool `json:"enabled"`
- ProviderURL string `json:"provider_url"`
- ProviderName string `json:"provider_name"`
- ClientID string `json:"client_id"`
- ClientSecret string `json:"client_secret"`
- AutoCreateUsers bool `json:"auto_create_users"`
- DefaultUserRoleID null.Int `json:"default_user_role_id"`
- DefaultListRoleID null.Int `json:"default_list_role_id"`
+ Enabled bool `json:"enabled"`
+ ProviderURL string `json:"provider_url"`
+ ProviderName string `json:"provider_name"`
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret"`
+ AutoCreateUsers bool `json:"auto_create_users"`
+ DefaultUserRoleID null.Int `json:"default_user_role_id"`
+ DefaultListRoleID null.Int `json:"default_list_role_id"`
+ Roles []OIDCRoleMapping `json:"roles"`
} `json:"security.oidc"`
SecurityTrustedURLs []string `json:"security.trusted_urls"`
diff --git a/schema.sql b/schema.sql
index 5b3c08d6..581addbc 100644
--- a/schema.sql
+++ b/schema.sql
@@ -261,7 +261,7 @@ INSERT INTO settings (key, value) VALUES
('privacy.domain_allowlist', '[]'),
('privacy.record_optin_ip', 'false'),
('security.captcha', '{"altcha": {"enabled": false, "complexity": 300000}, "hcaptcha": {"enabled": false, "key": "", "secret": ""}}'),
- ('security.oidc', '{"enabled": false, "provider_url": "", "provider_name": "", "client_id": "", "client_secret": "", "auto_create_users": false, "default_user_role_id": null, "default_list_role_id": null}'),
+ ('security.oidc', '{"enabled": false, "provider_url": "", "provider_name": "", "client_id": "", "client_secret": "", "auto_create_users": false, "default_user_role_id": null, "default_list_role_id": null, "roles": []}'),
('security.trusted_urls', '[]'),
('upload.provider', '"filesystem"'),
('upload.max_file_size', '5000'),
diff --git a/static/admin/assets/js/views/settings.js b/static/admin/assets/js/views/settings.js
index 45e4301d..c0051568 100644
--- a/static/admin/assets/js/views/settings.js
+++ b/static/admin/assets/js/views/settings.js
@@ -50,6 +50,11 @@ function component(settings, userRoles, listRoles) {
// Normalize the raw settings into a display-friendly form (mirrors the old getSettings()).
const normalize = (data) => {
const d = JSON.parse(JSON.stringify(data));
+ d['security.oidc'].default_user_role_id ||= '';
+ d['security.oidc'].default_list_role_id ||= '';
+ d['security.oidc'].roles = (d['security.oidc'].roles || []).map((r) => ({
+ ...r, user_role_id: r.user_role_id ?? '', list_role_id: r.list_role_id ?? '',
+ }));
// Serialize the email_headers map to a display string.
for (let i = 0; i < d.smtp.length; i += 1) {
@@ -417,6 +422,10 @@ function component(settings, userRoles, listRoles) {
? parseInt(form['security.oidc'].default_user_role_id, 10) : null;
form['security.oidc'].default_list_role_id = form['security.oidc'].default_list_role_id
? parseInt(form['security.oidc'].default_list_role_id, 10) : null;
+ form['security.oidc'].roles.forEach((r) => {
+ r.user_role_id = r.user_role_id ? parseInt(r.user_role_id, 10) : null;
+ r.list_role_id = r.list_role_id ? parseInt(r.list_role_id, 10) : null;
+ });
// Strip display-only fields.
form.smtp.forEach((s) => { delete s.strEmailHeaders; delete s.showHeaders; });
diff --git a/static/admin/partials/settings/security.html b/static/admin/partials/settings/security.html
index e53dad51..eab32525 100644
--- a/static/admin/partials/settings/security.html
+++ b/static/admin/partials/settings/security.html
@@ -1,7 +1,7 @@
{{ define "settings-security" -}}
{{- $d := .Data -}}
<div class="settings-items">
- <fieldset class="card" data-keywords="oidc sso single sign-on openid connect authentication login provider identity">
+ <fieldset class="card" data-keywords="oidc sso single sign-on openid connect authentication login provider identity roles mapping claims groups">
<legend>{{ .L.T "settings.security.enableOIDC" }}</legend>
<label data-field>
<input type="checkbox" role="switch" x-model="form['security.oidc'].enabled" />
@@ -60,9 +60,11 @@
<fieldset :disabled="!form['security.oidc'].auto_create_users">
+ <legend>{{ .L.T "users.roles" }}</legend>
<div data-field>
<label for="oidc-user-role">{{ .L.T "settings.security.OIDCDefaultUserRole" }}</label>
- <select id="oidc-user-role" x-model="form['security.oidc'].default_user_role_id">
+ <select id="oidc-user-role" required x-model="form['security.oidc'].default_user_role_id">
+ <option value="" disabled>&mdash;</option>
{{- range $d.UserRoles }}
<option value="{{ .ID }}">{{ .Name }}</option>
{{- end }}
@@ -80,6 +82,53 @@
</select>
<small data-hint>{{ .L.T "settings.security.OIDCDefaultRoleHelp" }}</small>
</div>
+
+ </fieldset>
+
+ <fieldset class="card" :disabled="!form['security.oidc'].auto_create_users">
+ <legend>{{ .L.T "settings.security.OIDCRoleMapping" }}</legend>
+ <p data-hint>{{ .L.T "settings.security.OIDCRoleMappingHelp" }}</p>
+ <template x-for="(mapping, n) in form['security.oidc'].roles" :key="n">
+ <fieldset class="card">
+ <legend x-text="`#${n + 1}`"></legend>
+ <div class="row">
+ <label class="col-6" data-field>
+ {{ .L.T "settings.security.OIDCClaim" }}
+ <input required placeholder="groups" x-model="mapping.claim" />
+ </label>
+ <label class="col-6" data-field>
+ {{ .L.T "globals.terms.value" }}
+ <input required placeholder="editors" x-model="mapping.match" />
+ </label>
+ </div>
+ <div class="row">
+ <label class="col-6" data-field>
+ {{ .L.Tc "users.userRole" 1 }}
+ <select x-model="mapping.user_role_id">
+ <option value="">&mdash; {{ .L.T "globals.terms.default" }} &mdash;</option>
+ {{- range $d.UserRoles }}
+ <option value="{{ .ID }}">{{ .Name }}</option>
+ {{- end }}
+ </select>
+ </label>
+ <label class="col-6" data-field>
+ {{ .L.Tc "users.listRole" 2 }}
+ <select x-model="mapping.list_role_id">
+ <option value="">&mdash; {{ .L.T "globals.terms.default" }} &mdash;</option>
+ {{- range $d.ListRoles }}
+ <option value="{{ .ID }}">{{ .Name }}</option>
+ {{- end }}
+ </select>
+ </label>
+ </div>
+ <button type="button" class="outline small" data-variant="danger" @click="form['security.oidc'].roles.splice(n, 1)">
+ {{ Icon "trash-2" }} {{ .L.T "globals.buttons.remove" }}
+ </button>
+ </fieldset>
+ </template>
+ <button type="button" class="outline small" @click="form['security.oidc'].roles.push({ claim: '', match: '', user_role_id: '', list_role_id: '' })">
+ {{ Icon "plus" }} {{ .L.T "globals.buttons.addNew" }}
+ </button>
</fieldset>
</div>
</template>