Skip to content

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

Add support for OIDC-logout. Closes #2143.

Kailash Nadh524039e59bf8
diff --git a/cmd/auth.go b/cmd/auth.go
index 49c278e0..fa80f2ac 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -167,11 +167,28 @@ func (a *App) TwofaPage(c echo.Context) error {
// Logout logs a user out.
func (a *App) Logout(c echo.Context) error {
- // Delete the session from the DB and cookie.
sess := c.Get(auth.SessionKey).(*simplesessions.Session)
+ token, err := sess.String(sess.Get("oidc_token"))
+ if err != nil {
+ a.log.Printf("error reading OIDC session token: %v", err)
+ }
+
+ // Delete the session from the DB and cookie.
_ = sess.Destroy()
- return c.JSON(http.StatusOK, okResp{true})
+ // There might be an OIDC logout URL to redirect to.
+ var logoutURL string
+ if err == nil && token != "" {
+ logoutURL, err = a.auth.GetOIDCLogoutURL(token, a.urlCfg.RootURL+uriAdmin+"/login")
+ if err != nil {
+ a.log.Printf("error getting OIDC logout URL: %v", err)
+ }
+ }
+
+ return c.JSON(http.StatusOK, struct {
+ okResp
+ RedirectURL null.String `json:"redirect_url"`
+ }{okResp{true}, null.NewString(logoutURL, logoutURL != "")})
}
// OIDCLogin initializes an OIDC request and redirects to the OIDC provider for login.
diff --git a/cmd/init.go b/cmd/init.go
index 8e112b72..69f816a8 100644
--- a/cmd/init.go
+++ b/cmd/init.go
@@ -110,6 +110,7 @@ type Config struct {
Security struct {
OIDC struct {
Enabled bool `koanf:"enabled"`
+ Logout bool `koanf:"logout"`
ProviderURL string `koanf:"provider_url"`
ProviderName string `koanf:"provider_name"`
ClientID string `koanf:"client_id"`
@@ -1404,6 +1405,7 @@ func initAuth(co *core.Core, db *sql.DB, ko *koanf.Koanf) (bool, *auth.Auth) {
if ko.Bool("security.oidc.enabled") {
oidcCfg = auth.OIDCConfig{
Enabled: true,
+ Logout: ko.Bool("security.oidc.logout"),
ProviderURL: ko.String("security.oidc.provider_url"),
ClientID: ko.String("security.oidc.client_id"),
ClientSecret: ko.String("security.oidc.client_secret"),
diff --git a/docs/docs/content/oidc.md b/docs/docs/content/oidc.md
index 318c77dd..37e95b31 100644
--- a/docs/docs/content/oidc.md
+++ b/docs/docs/content/oidc.md
@@ -3,6 +3,8 @@
Listmonk supports single sign-on with OIDC (OpenID Connect). Any standards compliant OIDC provider can be configured in Settings -> Security -> OIDC
+Enable **OIDC RP-initiated logout** in Settings → Security to redirect to the provider's logout endpoint when logging out of an OIDC session, if the provider supports OIDC logout. This option is disabled by default. Register `https://listmonk.yoursite.com/admin/login` (including any configured root URL path) as an allowed post-logout redirect URI with the provider.
+
### 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). If role mapping is enabled, newly created users (on first OIDC login) can be auto-assigned roles mapped to OIDC claims.
diff --git a/i18n/en.json b/i18n/en.json
index 522f5419..16a3ed69 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -582,6 +582,7 @@
"settings.privacy.recordOptinIP": "Record opt-in IP address",
"settings.privacy.recordOptinIPHelp": "Record IP address of double opt-ins in subscriber attributes.",
"settings.restart": "Restart",
+ "settings.security.OIDCLogout": "OIDC RP-initiated logout",
"settings.security.OIDCClientID": "Client ID",
"settings.security.OIDCClientSecret": "Client secret",
"settings.security.OIDCHelp": "Enable OpenID Connect OAuth2 login via an OAuth provider.",
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
index 403822e6..e053cff1 100644
--- a/internal/auth/auth.go
+++ b/internal/auth/auth.go
@@ -12,6 +12,7 @@ import (
"fmt"
"log"
"net/http"
+ "net/url"
"slices"
"strings"
"sync"
@@ -36,6 +37,7 @@ type OIDCclaim struct {
type OIDCConfig struct {
Enabled bool `json:"enabled"`
+ Logout bool `json:"logout"`
ProviderURL string `json:"provider_url"`
RedirectURL string `json:"redirect_url"`
ClientID string `json:"client_id"`
@@ -442,6 +444,39 @@ func (o *Auth) SaveSession(u User, oidcToken string, c echo.Context) error {
return nil
}
+// GetOIDCLogoutURL returns the provider's logout URL if logout is enabled and supported, or an empty string.
+func (o *Auth) GetOIDCLogoutURL(token, redirectURL string) (string, error) {
+ if token == "" || !o.cfg.OIDC.Enabled || !o.cfg.OIDC.Logout {
+ return "", nil
+ }
+
+ provider, err := o.getProvider()
+ if err != nil {
+ return "", err
+ }
+
+ var meta struct {
+ EndSessionEndpoint string `json:"end_session_endpoint"`
+ }
+ if err := provider.Claims(&meta); err != nil {
+ return "", err
+ }
+ if meta.EndSessionEndpoint == "" {
+ return "", nil
+ }
+
+ u, err := url.Parse(meta.EndSessionEndpoint)
+ if err != nil {
+ return "", err
+ }
+ q := u.Query()
+ q.Set("id_token_hint", token)
+ q.Set("post_logout_redirect_uri", redirectURL)
+ u.RawQuery = q.Encode()
+
+ return u.String(), nil
+}
+
// GetSessionID returns the current session ID from the echo context.
func GetSessionID(c echo.Context) string {
sess, ok := c.Get(SessionKey).(*simplesessions.Session)
diff --git a/internal/migrations/v7.0.0.go b/internal/migrations/v7.0.0.go
index 6d7f0d15..4781b2c8 100644
--- a/internal/migrations/v7.0.0.go
+++ b/internal/migrations/v7.0.0.go
@@ -9,18 +9,17 @@ import (
)
func V7_0_0(db *sqlx.DB, fs stuffbin.FileSystem, ko *koanf.Koanf, lo *log.Logger) error {
- // Migrate existing `from_email` to `from_email[]`.
- if _, err := db.Exec(`UPDATE settings SET value = JSONB_BUILD_ARRAY(value) WHERE key = 'app.from_email' AND JSONB_TYPEOF(value) = 'string';`); err != nil {
- return err
- }
+ // Settings.
+ if _, err := db.Exec(`
+ -- Migrate existing from_email to from_email[].
+ UPDATE settings SET value = JSONB_BUILD_ARRAY(value)
+ WHERE key = 'app.from_email' AND JSONB_TYPEOF(value) = 'string';
- // Login session duration.
- if _, err := db.Exec(`INSERT INTO settings (key, value) VALUES ('security.session_duration', '"7d"') ON CONFLICT (key) DO NOTHING;`); err != nil {
- return err
- }
+ -- Login session duration.
+ INSERT INTO settings (key, value) VALUES ('security.session_duration', '"7d"')
+ ON CONFLICT (key) DO NOTHING;
- // Add `exclude_from_default` field to all SMTP servers.
- if _, err := db.Exec(`
+ -- Add exclude_from_default field to all SMTP servers.
UPDATE settings
SET value = (
SELECT JSONB_AGG(
@@ -33,12 +32,15 @@ func V7_0_0(db *sqlx.DB, fs stuffbin.FileSystem, ko *koanf.Koanf, lo *log.Logger
SELECT 1 FROM JSONB_ARRAY_ELEMENTS(value) AS v
WHERE NOT (v ? 'exclude_from_default')
);
- `); err != nil {
- return err
- }
- // 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 {
+ -- OIDC RP-initiated logout option.
+ UPDATE settings SET value = JSONB_SET(value, '{logout}', 'false'::JSONB)
+ WHERE key = 'security.oidc' AND NOT (value ? 'logout');
+
+ -- OIDC claim mapping.
+ UPDATE settings SET value = JSONB_SET(value, '{roles}', '[]'::JSONB)
+ WHERE key = 'security.oidc' AND NOT (value ? 'roles');
+ `); err != nil {
return err
}
diff --git a/models/settings.go b/models/settings.go
index a936badd..bbfb4160 100644
--- a/models/settings.go
+++ b/models/settings.go
@@ -64,6 +64,7 @@ type Settings struct {
OIDC struct {
Enabled bool `json:"enabled"`
+ Logout bool `json:"logout"`
ProviderURL string `json:"provider_url"`
ProviderName string `json:"provider_name"`
ClientID string `json:"client_id"`
diff --git a/schema.sql b/schema.sql
index 233ccf98..92b3e76e 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, "roles": []}'),
+ ('security.oidc', '{"enabled": false, "provider_url": "", "provider_name": "", "client_id": "", "client_secret": "", "auto_create_users": false, "logout": false, "default_user_role_id": null, "default_list_role_id": null, "roles": []}'),
('security.trusted_urls', '[]'),
('security.session_duration', '"7d"'),
('upload.provider', '"filesystem"'),
diff --git a/static/admin/assets/js/main.js b/static/admin/assets/js/main.js
index bb053dbd..e9fb9309 100644
--- a/static/admin/assets/js/main.js
+++ b/static/admin/assets/js/main.js
@@ -1,5 +1,5 @@
-import Alpine from 'alpinejs';
import '@knadh/oat';
+import Alpine from 'alpinejs';
import { I18n } from './i18n.js';
import { register as registerTable } from './table.js';
import * as u from './utils.js';
@@ -65,6 +65,12 @@ function setupAlpine() {
}).catch(() => { });
}, 500);
},
+
+ async onLogout(logoutURL, loginURL) {
+ const resp = await fetch(logoutURL, { method: 'POST' });
+ const out = await resp.json();
+ window.location.href = out.redirect_url || loginURL;
+ },
}));
}
diff --git a/static/admin/partials/settings/security.html b/static/admin/partials/settings/security.html
index c9aa956e..faca232d 100644
--- a/static/admin/partials/settings/security.html
+++ b/static/admin/partials/settings/security.html
@@ -62,7 +62,12 @@
<hr />
- <label data-field>
+ <label data-field class="w-100">
+ <input type="checkbox" role="switch" x-model="form['security.oidc'].logout" />
+ {{ .L.T "settings.security.OIDCLogout" }}
+ </label>
+
+ <label data-field class="w-100">
<input type="checkbox" role="switch" x-model="form['security.oidc'].auto_create_users" />
{{ .L.T "settings.security.OIDCAutoCreateUsers" }}
<small data-hint>{{ .L.T "settings.security.OIDCAutoCreateUsersHelp" }}</small>
diff --git a/static/admin/views/base.html b/static/admin/views/base.html
index cc58eda5..f66d699a 100644
--- a/static/admin/views/base.html
+++ b/static/admin/views/base.html
@@ -69,7 +69,7 @@
</button>
<menu popover id="user-menu">
<a href="{{ URI "/admin/user/profile" }}" role="menuitem" class="button ghost">{{ Icon "user" }} {{ $.L.T "users.profile" }}</a>
- <button type="button" role="menuitem" class="ghost" onclick="fetch('{{ URI "/api/logout" }}', { method: 'POST' }).then(() => { document.location.href = '{{ URI "/admin/login" }}'; })">
+ <button type="button" role="menuitem" class="ghost" @click="onLogout('{{ URI "/api/logout" }}', '{{ URI "/admin/login" }}')">
{{ Icon "log-out" }} {{ $.L.T "users.logout" }}
</button>
<hr />