oauthpopup

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

oauthpopup

Sign in with a provider in a popup and hand the new session to the page that opened it. It is for an app embedded on another site (an iframe in a customer's page) where the browser partitions or blocks third-party cookies: the popup is a first-party window on the auth origin, the sign-in completes there, and a completion page posts the session token to the opener, which sends it as Authorization: Bearer from then on.

It is a package of the oauthproxy module (both are opt-in browser-flow companions of plugin/oauth with no dependency of their own) and shares nothing with the proxy, so an app imports only the one it uses.

pp := oauthpopup.New()
a, err := auth.New(auth.WithBaseURL("https://auth.example.com"), auth.WithSecret(secret),
	auth.WithTrustedOrigins("https://embed.customer.com"),
	auth.WithPlugins(oauth.New(oauth.WithProviders(oauth.Google(id, s))), pp))

mux.Handle("/auth/", authhttp.Handler(a, authhttp.Prefix("/auth")))
mux.Handle(oauthpopup.DefaultMount+"/", http.StripPrefix(oauthpopup.DefaultMount, pp.Handler()))

Routes

Route What it does
GET /auth/oauthpopup/start provider, popupOrigin (must be trusted, else 403), popupNonce, callbackURL, newUserCallbackURL (each must pass TrustsReturnURL), scopes (comma list), requestSignUp=true, additionalData; sets the sealed marker cookie __Host-auth_popup (10 minutes) and starts the oauth plugin's flow with the completion page as its return and error page
GET /auth/oauthpopup/complete Opens and expires the marker, then renders a page that posts {type: "ubgo-auth:oauth-popup", nonce, token, redirectTo, error} to the opener at popupOrigin and closes

The completion page hands out only a session created after the marker, so an existing session can never be fished out of the cookie, and only once, because the marker is expired on first use. Its script is fixed and pinned by hash (ScriptCSPHash) in Content-Security-Policy: default-src 'none'; script-src 'sha256-…'; base-uri 'none'; the per-request data sits in an inert JSON element, escaped by encoding/json. The answer is Cache-Control: no-store and Referrer-Policy: no-referrer.

Error codes the page posts: popup_sign_in_failed, invalid_callback_url, invalid_new_user_callback_url, provider_not_found, or the oauth plugin's code (oauth.provider_failed, …) for a failure after the state check. A provider-side denial before the state check follows the oauth plugin's ErrorURL (or auth.WithErrorURL); point it at the completion page if popups are the only browser flow.

RewriteCallback(next) is an after hook on the callback: wrapping the handler that serves the oauth routes, it answers a popup sign-in's callback (marker cookie present, redirect to <mount>/complete on the same host) with the completion page instead of the redirect, built by complete from the request's cookies plus the ones the callback set, so the marker and new-session checks are unchanged. Anything else passes through; responses are buffered only while a marker cookie is present.

The opener

const nonce = crypto.randomUUID();
const popup = window.open(`https://auth.example.com/auth/oauthpopup/start?provider=google&popupOrigin=${encodeURIComponent(location.origin)}&popupNonce=${nonce}`, "signin", "width=500,height=600");
window.addEventListener("message", (e) => {
  if (e.origin !== "https://auth.example.com" || e.data?.type !== "ubgo-auth:oauth-popup" || e.data.nonce !== nonce) return;
  if (e.data.error) return showError(e.data.error);
  sessionStorage.setItem("auth", e.data.token); // send as Authorization: Bearer
});

The opener page must allow popups to keep their opener (Cross-Origin-Opener-Policy: same-origin-allow-popups or none), and the auth origin's callback must not send a COOP header that severs it.

Security

The token is a bearer credential: any script on the opener's origin can read it, which is the purpose and the risk. Trust only the origins that embed you, and keep such sessions short (auth.WithSessionPolicy).

Documentation

Overview

Package oauthpopup runs a provider sign-in in a popup and hands the new session to the page that opened it. It is for an app embedded on another site (an iframe in a customer's page), where the browser partitions or blocks third-party cookies: the popup is a first-party window on the auth origin, so the sign-in completes there, and the completion page posts the session token to the opener, which then sends it as Authorization: Bearer.

It lives beside oauthproxy because both are opt-in browser-flow companions of plugin/oauth with no dependency of their own; it is its own package because it shares nothing with the proxy, and an app imports only the one it uses.

The flow:

GET <mount>/start?provider=google&popupOrigin=https://app.customer.com&popupNonce=…
    checks popupOrigin is trusted, sets a sealed marker cookie (origin,
    nonce, time), and starts the oauth plugin's flow with this package's
    completion page as returnTo and errorTo.
GET <mount>/complete
    opens and expires the marker; hands out only a session created after
    the marker, so a page can never fish an existing session out of the
    cookie; renders a page whose fixed script posts {type, nonce, token,
    redirectTo, error} to the opener at popupOrigin and closes.

The token is a bearer credential: any script on the opener's origin can read it, which is the point and the risk. Keep such sessions short.

Index

Constants

View Source
const (
	// MessageType is the type of the posted message.
	//ds:def id=oauthpopup-messagetype-3w8kq5nv owner=@khanakia stability=stable
	MessageType = "ubgo-auth:oauth-popup"
	// DataElementID is the id of the inert JSON element on the page.
	DataElementID = "ubgo-auth-oauth-popup"
	// MarkerCookie holds the sealed marker between start and completion.
	MarkerCookie = "__Host-auth_popup"
	// DefaultMount is where the app mounts Handler: the oauth plugin's mount
	// prefix and this plugin's name.
	DefaultMount = oauth.DefaultMountPrefix + "/" + PluginName
	// MarkerTTL is how long a popup sign-in may take, 10 minutes.
	//ds:def id=oauthpopup-markerttl-5q2xn7wk owner=@khanakia stability=stable
	MarkerTTL = 10 * time.Minute
)

Names that cross to the browser.

View Source
const (
	ErrorSignInFailed = "popup_sign_in_failed"
	ErrorBadCallback  = "invalid_callback_url"
	ErrorBadErrorURL  = "invalid_error_callback_url"
	ErrorBadNewUser   = "invalid_new_user_callback_url"
	ErrorNoProvider   = "provider_not_found"
)

Error codes the page posts.

View Source
const PluginName = "oauthpopup"

PluginName is the plugin's permanent identity.

Variables

View Source
var ErrUntrustedOrigin = auth.NewError("oauthpopup.untrusted_origin", http.StatusForbidden, "This page may not open a sign-in popup.")

ErrUntrustedOrigin answers a start whose popupOrigin the app does not trust.

View Source
var ScriptCSPHash = func() string {
	h := sha256.Sum256([]byte(completionScript))
	return "'sha256-" + base64.StdEncoding.EncodeToString(h[:]) + "'"
}()

ScriptCSPHash is the CSP source of completionScript.

Functions

func StartURL

func StartURL(base, provider, popupOrigin, nonce string) string

StartURL is the start link an opener page opens in its popup, for a Go page that renders it; base is the auth origin.

Types

type Option

type Option func(*Plugin)

Option configures the plugin.

func HTTPOptions

func HTTPOptions(opts ...authhttp.Option) Option

HTTPOptions are the authhttp options the app's handler uses (cookie prefix, trusted proxies), so this handler reads the same cookies.

func Mount

func Mount(path string) Option

Mount overrides DefaultMount, the path Handler is served under; the completion page's URL is built from it.

type Plugin

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin is the popup plugin. Build it with New.

func New

func New(opts ...Option) *Plugin

New builds the plugin.

func (*Plugin) Handler

func (p *Plugin) Handler() http.Handler

Handler serves start and complete. Mount it with the prefix stripped:

mux.Handle(oauthpopup.DefaultMount+"/", http.StripPrefix(oauthpopup.DefaultMount, pp.Handler()))

func (*Plugin) Init

func (p *Plugin) Init(a *auth.Auth) error

Init finds the oauth plugin.

func (*Plugin) Name

func (p *Plugin) Name() string

Name returns PluginName.

func (*Plugin) Requires

func (p *Plugin) Requires() []string

Requires names the oauth plugin, which runs the sign-in.

func (*Plugin) RewriteCallback

func (p *Plugin) RewriteCallback(next http.Handler) http.Handler

RewriteCallback is an after hook on the provider callback: wrap the handler that serves the oauth plugin's routes with it, and a callback that ends a popup sign-in (the marker cookie is present and the callback redirects to this plugin's completion page) answers with the completion page itself instead of the redirect, carrying the session the callback just issued, or its error. Every other response passes through unchanged.

mux.Handle("/auth/", pp.RewriteCallback(authhttp.Handler(a, authhttp.Prefix("/auth"))))

It saves the browser one request and changes nothing else: the page is built by the same code as GET <mount>/complete, from the cookies the callback set, so it still spends the marker and still hands out only a session created after the marker. Without it the redirect reaches /complete, with the same outcome. Responses are buffered only while a marker cookie is present.

func (*Plugin) Validate

func (p *Plugin) Validate(c *auth.Config) error

Validate derives the marker key: the plugin needs auth.WithSecret.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL