oauth2

package
v14.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 31 Imported by: 0

README

OAuth2 Documentation

This package runs an OAuth 2.0 server on Iris, and covers the standard flows on the client side. What follows is how to configure the server, then how to drive each flow from a client.

Server-Side Overview

Below is a full example of how to create and configure an OAuth2 server based on the attached code. We'll break it down into parts.

1. Defining the User Type and Provider
package main

import (
	"context"
	"fmt"
	"sync"
	"uuid"

	"github.com/kataras/iris/v14/auth"
)

// User holds the user information.
type User struct {
	ID    string `json:"id"`
	Email string `json:"email"`
}

// Provider is a mock user data store.
type Provider struct {
	dataset []User
	mu      sync.RWMutex
}

func NewProvider() *Provider {
	return &Provider{
		dataset: []User{
			{
				ID:    uuid.New().String(),
				Email: "kataras2006@hotmail.com",
			},
			{
				ID:    uuid.New().String(),
				Email: "example@example.com",
			},
		},
	}
}

func (p *Provider) Signin(ctx context.Context, username, password string) (User, error) {
	p.mu.RLock()
	defer p.mu.RUnlock()

	// Simple example: check only username (email). Password not validated here.
	for _, user := range p.dataset {
		if user.Email == username {
			return user, nil
		}
	}

	return User{}, fmt.Errorf("user not found")
}

func (p *Provider) ValidateToken(ctx context.Context, claims auth.StandardClaims, u User) error {
	return nil
}

func (p *Provider) InvalidateToken(ctx context.Context, claims auth.StandardClaims, u User) error {
	return nil
}

func (p *Provider) InvalidateTokens(ctx context.Context, u User) error {
	return nil
}
  1. We define a simple User struct to represent an authenticated user.
  2. Provider implements the Iris auth interfaces to handle user sign-in and token validation.
2. Loading the Auth Configuration (auth.yml example)
Headers:
  - "Authorization"
  - "X-Authorization"
Cookie:
  Name: "iris_auth_cookie"
  Secure: false
  Hash: "D*G-KaPdSgUkXp2s5v8y/B?E(H+MbQeThWmYq3t6w9z$C&F)J@NcRfUjXn2r4u7x"
  Block: "VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!"
Keys:
  - ID: IRIS_AUTH_ACCESS
    Alg: EdDSA
    MaxAge: 2h
    Private: |+
      -----BEGIN PRIVATE KEY-----
      MC4CAQAwBQYDK2VwBCIEIFdZWoDdFny5SMnP9Fyfr8bafi/B527EVZh8JJjDTIFO
      -----END PRIVATE KEY-----
    Public: |+
      -----BEGIN PUBLIC KEY-----
      MCowBQYDK2VwAyEAzpgjKSr9E032DX+foiOxq1QDsbzjLxagTN+yVpGWZB4=
      -----END PUBLIC KEY-----
  - ID: IRIS_AUTH_REFRESH
    Alg: EdDSA
    MaxAge: 720h
    Private: |+
      -----BEGIN PRIVATE KEY-----
      MC4CAQAwBQYDK2VwBCIEIHJ1aoIjA2sRp5eqGjGR3/UMucrHbBdBv9p8uwfzZ1KZ
      -----END PRIVATE KEY-----
    Public: |+
      -----BEGIN PUBLIC KEY-----
      MCowBQYDK2VwAyEAsKKAr+kDtfAqwG7cZdoEAfh9jHt9W8qi9ur5AA1KQAQ=
      -----END PUBLIC KEY-----
    EncryptionKey: 0123456789abcdef0123456789abcdef

These keys and cookies allow Iris to sign and store tokens securely.

3. Main Server Setup
package main

import (
	"context"
	"fmt"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/auth"
	"github.com/kataras/iris/v14/auth/oauth2"
	"github.com/kataras/iris/v14/middleware/view"

	"github.com/kataras/blocks"
)

func main() {
	app := iris.New()

	// Load templates from ./views directory.
	templates := blocks.New("./views")
	if err := templates.Load(); err != nil {
		panic(err)
	}
	app.UseRouter(view.Handler(templates))

	// 1) Load Auth configuration from auth.yml
	authConfig, err := auth.LoadConfiguration("./auth.yml")
	if err != nil {
		panic(err)
	}
	s, err := auth.New[User](authConfig)
	if err != nil {
		panic(err)
	}
	s.AddProvider(NewProvider())

	// 2) Define routes:
	app.Get("/signin", renderSigninForm)
	app.Post("/signin", s.SigninHandler)
	app.Get("/consent", renderConsentForm())

	// 3) Create the OAuth2 server instance:
	// The client store keeps the registered clients. The in-memory one is
	// enough for this example; use oauth2.NewPostgresClientStore("clients", pool)
	// with a pgxpool.Pool to persist them.
	oauth2Server := oauth2.New(s,
		oauth2.WithClientStore(oauth2.NewMemoryClientStore()),
		oauth2.WithLoginPageURL("/signin"),
		oauth2.WithConsentPageURL("/consent"),
		oauth2.WithDeviceInterval(5),
	)

	// 4) Register a mock client:
	myClient, err := oauth2Server.RegisterClient(context.Background(), oauth2.ClientRegistration{
		Name:            "Example-Client-Name",
		Website:         "https://www.iris-go.com",
		LogoURL:         "https://www.iris-go.com/images/logo.png",
		RedirectURI:     "http://localhost:8081/callback",
		VerificationURI: "http://localhost:8081/device_verification",
		GrantTypes:      []string{oauth2.GrantTypeAuthorizationCode, oauth2.GrantTypeDeviceCode, oauth2.GrantTypeRefreshToken, oauth2.GrantTypePassword},
		Scopes:          []string{"profile", "email:*"}, // allowed scopes and resource-action policy example.
		CodeMaxAge:      3600,   // max age for codes, in seconds.
		AccessMaxAge:    3600,   // max age for access tokens, in seconds.
		RefreshMaxAge:   604800, // max age for refresh tokens, in seconds.
	})
	if err != nil {
		panic(err)
	}
	fmt.Printf("ClientID:     %s\nClientSecret: %s\n", myClient.ID, myClient.Secret)

	// 5) Attach the OAuth2 routes under /oauth2:
	app.Router("/oauth2", oauth2Server)


	// Register the VerifyHandler to protect the routes.
	userRouter := app.Router("/user", s.VerifyHandler())                  
	// AllowScopes is a middleware that checks if the user has the required scopes.
	userRouter.Get("/profile", oauth2.AllowScopes("profile"), getProfile)
	// This will fire a 403 Forbidden if the user does not have both "profile" and "email" scopes
	// or it's not directly logged-in to the application.
	userRouter.Get("/email", oauth2.AllowScopes("profile", "email:read"), getEmail)

	app.Listen(":8080")
}

func getProfile(ctx iris.Context) {
	clientClaims, err := oauth2.GetClientClaims(ctx) // example of getting the oauth2 client claims.
	if err == nil {
		ctx.Writef("Request made by client: %#+v\n", clientClaims)
	}

	user := auth.GetUser[User](ctx) // example of getting the custom user claims.
	ctx.WriteString(user.ID)
}

func getEmail(ctx iris.Context) {
	clientClaims, err := oauth2.GetClientClaims(ctx)
	if err == nil {
		ctx.Writef("Request made by client: %#+v\n", clientClaims)
	}

	user := auth.GetUser[User](ctx)
	ctx.WriteString(user.Email)
}

func renderSigninForm(ctx iris.Context) {
	// Renders a basic sign-in form found in ./views/signin.html
	if err := view.Render(ctx, "signin", "main", iris.Map{"Title": "Signin Page"}); err != nil {
		ctx.HTML(fmt.Sprintf("<h3>%s</h3>", err.Error()))
	}
}

func renderConsentForm() iris.Handler {
	type Request struct {
		ClientID      string `url:"client_id"`
		ClientName    string `url:"client_name"`
		ClientWebsite string `url:"client_website"`
		ClientLogoURL string `url:"client_logo_url"`
		State         string `url:"state"`
		Scope         string `url:"scope"`
	}

	return func(ctx iris.Context) {
		var req Request
		if err := ctx.ReadQuery(&req); err != nil {
			ctx.HTML(fmt.Sprintf("<h3>Error reading query: %s</h3>", err.Error()))
			return
		}

		tmplData := struct {
			Request
			Title  string
			Scopes []string
		}{
			Request: req,
			Title:   "Consent Page",
			Scopes:  oauth2.SplitScopes(req.Scope),
		}

		if err := view.Render(ctx, "oauth2/consent", "main", tmplData); err != nil {
			ctx.HTML(fmt.Sprintf("<h3>%s</h3>", err.Error()))
		}
	}
}
Explanation:
  1. We initialize a simple Iris application.
  2. We load templates and use the View middleware so we can render forms.
  3. We load the “auth.yml” to configure signing keys and cookies.
  4. We create an auth.Auth[User] instance, adding our custom Provider.
  5. We create a new oauth2.Server[User] to handle OAuth flows. We set custom LoginPageURL and ConsentPageURL.
  6. We register a mock client with RegisterClient(), you can do the same through the client's store as well.
  7. Finally, we map oauth2Server to the route prefix /oauth2. This automatically registers the necessary authorization/token/device endpoints; /oauth2/auth, /oauth2/token and /oauth2/device/code routes.

Client-Side Usage

Below are quick examples for each OAuth2 flow using just the "golang.org/x/oauth2" and "net/http" packages.

Authorization Code Flow
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"golang.org/x/oauth2"
)

var authConfig = &oauth2.Config{
	ClientID:     "my-client-id",
	ClientSecret: "my-secret",
	Endpoint: oauth2.Endpoint{
		AuthURL:  "http://localhost:8080/oauth2/authorize",
		TokenURL: "http://localhost:8080/oauth2/token",
	},
	RedirectURL: "http://localhost:8081/callback",
	Scopes:      []string{"profile"},
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// 1) Redirect for authorization:
		url := authConfig.AuthCodeURL("random-state", oauth2.AccessTypeOffline)
		http.Redirect(w, r, url, http.StatusFound)
	})

	http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
		// 2) Exchange code for token:
		code := r.URL.Query().Get("code")
		state := r.URL.Query().Get("state")
		token, err := authConfig.Exchange(context.Background(), code, oauth2.SetAuthURLParam("state", state))
		if err != nil {
			http.Error(w, "Token exchange error: "+err.Error(), http.StatusInternalServerError)
			return
		}
		fmt.Fprintf(w, "Access Token: %s\n", token.AccessToken)
	})

	log.Println("Client listening on http://localhost:8081/")
	http.ListenAndServe(":8081", nil)
}

Steps to try it:

  1. Run the OAuth2 server on :8080.
  2. Run this client on :8081.
  3. Go to http://localhost:8081. It redirects to the server’s authorize endpoint.
  4. Login and approve if necessary; you’ll return with a code to /callback, which is exchanged for a token.
Device Code Flow
package main

import (
	"context"
	"fmt"
	"log"

	"golang.org/x/oauth2"
	devtools "golang.org/x/oauth2/device"
)

func main() {
	devConfig := &oauth2.Config{
		ClientID:     "my-client-id",
		ClientSecret: "my-secret",
		Endpoint: oauth2.Endpoint{
            AuthURL:       "http://localhost:8080/oauth2/authorize",
            TokenURL:      "http://localhost:8080/oauth2/token",
            DeviceAuthURL: "http://localhost:8080/oauth2/device/code",
		},
		Scopes: []string{"profile"},
	}

	deviceClient := devtools.Config{Config: *devConfig}
	ctx := context.Background()

	// 1) Request deviceauth
	deviceAuth, err := deviceClient.DeviceAuth(ctx)
	if err != nil {
		log.Fatalln("DeviceAuth Error:", err)
	}

	// Show user instructions
	fmt.Println("Go to:", deviceAuth.VerificationURI)
	fmt.Println("Enter Code:", deviceAuth.UserCode)

	// 2) Poll for token
	token, err := deviceClient.DeviceAccessToken(ctx, deviceAuth)
	if err != nil {
		log.Fatalln("DeviceAccessToken Error:", err)
	}

	fmt.Println("Access Token:", token.AccessToken)
}
Password Grant Flow
package main

import (
	"context"
	"fmt"
	"log"

	"golang.org/x/oauth2"
    "golang.org/x/oauth2/authhandler" // or your own password credential helper
)

func main() {
	passConfig := &oauth2.Config{
		ClientID:     "my-client-id",
		ClientSecret: "my-secret",
		Endpoint: oauth2.Endpoint{
            AuthURL:       "http://localhost:8080/oauth2/authorize",
            TokenURL:      "http://localhost:8080/oauth2/token",
            DeviceAuthURL: "http://localhost:8080/oauth2/device/code",
		},
		Scopes: []string{"profile"},
	}

	ctx := context.Background()

	// Suppose a username/password is given:
	username := "kataras2006@hotmail.com"
	password := "admin_$@#@1239182"

	token, err := authhandler.PasswordCredentialsToken(ctx, passConfig, username, password)
	if err != nil {
		log.Fatalln("Failed to obtain token:", err)
	}

	fmt.Println("Access Token:", token.AccessToken)
}
Refresh Token Flow

Refresh tokens are automatically handled by the client's OAuth2 package option but here is how you can handle refreshes manually:

package main

import (
	"context"
	"fmt"
	"log"

	"golang.org/x/oauth2"
)

func main() {
	config := &oauth2.Config{
		ClientID:     "my-client-id",
		ClientSecret: "my-secret",
		Endpoint: oauth2.Endpoint{
			TokenURL: "http://localhost:8080/oauth2/token",
		},
		Scopes: []string{"profile"},
	}

	ctx := context.Background()

	// Pretend we already have a token with a refresh token:
	oldToken := &oauth2.Token{
		AccessToken:  "the-old-access-token",
		RefreshToken: "the-refresh-token",
	}

	// 1) Create a TokenSource
	ts := config.TokenSource(ctx, oldToken)

	// 2) Request a new token (the library automatically handles refresh grant)
	newToken, err := ts.Token()
	if err != nil {
		log.Fatalln("Refresh Token Error:", err)
	}

	fmt.Println("New Access Token:", newToken.AccessToken)
}

Advanced Policy Engine and Open Policy Agent (OPA)

Open Policy Agent (OPA) is an open-source, general-purpose policy engine. It moves the authorization decision out of your application code and into policies you write once and apply across services.

Key Concepts
  1. Policy: A set of rules written in Rego, OPA’s policy language, that define what actions are allowed or denied.
  2. Data: JSON documents that provide context for policy decisions.
  3. Query: A request to evaluate a policy against a set of input data.
Benefits of Using OPA
  • Centralized Policy Management: Manage all policies in one place.
  • Flexibility: Write complex policies using Rego.
  • Decoupling: Separate policy logic from application code.
  • Consistency: Enforce policies consistently across different services.
Example: Integrating OPA with OAuth2
1. Define Policies in Rego

Create a policy file (e.g., policy.rego) that defines the rules for access control.

package authz

default allow = false

allow {
    input.client_id == "example-client"
    input.resource == "users"
    input.action == "read"
}

allow {
    input.client_id == "example-client"
    input.resource == "orders"
    input.action == "write"
}
2. Load Policies into OPA

Start OPA with the policy file.

opa run --server --addr :8181 policy.rego
3. Initialize the OPA Client
import "github.com/kataras/iris/v14/auth/oauth2/opa"
opaClient := opa.NewClient("http://localhost:8181/v1/data/authz/allow")
4. Usage in Routes

Use the OPA Client to define new policies and the AllowPolicies middleware in your routes (or group of routes) to enforce policies.

app.Get("/api/users",
    oauth2.AllowPolicies(opaClient.NewPolicy("uesrs", "read")),
    func(ctx iris.Context) {
        ctx.JSON(iris.Map{"message": "List of users..."})
    })

app.Post("/api/orders",
    oauth2.AllowPolicies(opaClient.NewPolicy("orders", "write")),
    func(ctx iris.Context) {
        ctx.JSON(iris.Map{"message": "Order created..."})
    })

With OPA in front of your OAuth2 server, an access rule lives in one policy instead of being spread across handlers, and every service that consults it decides the same way.

Documentation

Overview

Package oauth2 provides an implementation of OAuth2 server-related logic, including the registration and retrieval of clients, authorization codes, device codes, tokens, and consent handling.

Index

Constants

View Source
const (
	// DecisionApprove indicates the user approved the requested scopes.
	DecisionApprove = "approve"
	// DecisionDeny indicates the user denied the requested scopes.
	DecisionDeny = "deny"
)
View Source
const (
	// GrantTypeAuthorizationCode is the default grant type.
	// It's used when the client has an authorization code.
	GrantTypeAuthorizationCode = "authorization_code" // the default one.
	// GrantTypeDeviceCode is used when the client has a device code.
	GrantTypeDeviceCode = "urn:ietf:params:oauth:grant-type:device_code"
	// GrantTypePassword is used when the client has a username and password.
	GrantTypePassword = "password"
	// GrantTypeRefreshToken is used when the client wants to refresh the token.
	GrantTypeRefreshToken = "refresh_token"
)
View Source
const MaxAgeAccessToken = -1

Variables

View Source
var (
	// ErrClientNotFound is returned when the client is not found in the client store.
	ErrClientNotFound = fmt.Errorf("oauth2: client not found")
	// ErrClientAlreadyExists is returned by CreateClient when a client with the same name exists.
	ErrClientAlreadyExists = errors.New("oauth2: client already exists")
	// ErrClientMissing is returned when the client id and client secret are missing from the token.
	ErrClientMissing = errors.New("client id and client secret are required")
	// ErrClientMismatch is returned when the client's secret or version does not match
	// the stored client, or when the client_id claim does not match the token's audience.
	ErrClientMismatch = fmt.Errorf("client_id or secret or version mismatch")
)
View Source
var (
	// ErrClientTokenMissing is returned when the token does not contain any oauth2 client claims.
	ErrClientTokenMissing = fmt.Errorf("client token claims: %w", jwt.ErrMissing)
	// ErrClientInsufficientScopes is returned when the client does not have the required scopes.
	ErrClientInsufficientScopes = fmt.Errorf("client has insufficient scopes")
)
View Source
var Clock = jwt.Clock

Clock returns the current server's time. By default it returns the time.Now(). It can be overridden to return other time value.

Usage: now := Clock()

View Source
var ErrInvalidClientFilter = errors.New("oauth2: invalid client filter")

ErrInvalidClientFilter is returned by ListClients and CountClients when the filter is not valid, for example an unknown Sort field.

Functions

func AllowPolicies

func AllowPolicies(policies ...Policy) context.Handler

AllowPolicies returns a middleware that validates an OAuth2 client's access token for a given resource (and action). E.g. "users:read" (as ResourcePolicy{"users", "read"}), "users:*" or even "users".

Storing Policy-Like Scopes on the OAuth2 Client When registering a client, you can define resource-based scopes, e.g.:

client, err := oauth2Server.RegisterClient(ctx, oauth2.ClientRegistration{
	Name:            "ExampleClient",
	Website:         "https://example.com",
	LogoURL:         "https://example.com/logo.png",
	RedirectURI:     "https://localhost:8081/callback",
	VerificationURI: "...device_verification...",
	GrantTypes:      []string{"authorization_code", "refresh_token"},
	Scopes:          []string{"users:read", "users:write", "orders:read", "orders:write"}, // resource-based scopes
	CodeMaxAge:      3600,
	AccessMaxAge:    3600,
	RefreshMaxAge:   604800,
})

Usage:

app.Post("/",
	AuthInstance.VerifyHandler(),
	oauth2.AllowPolicies(oauth2.ResourcePolicy{Resource: "users", Action: "write"}),
	createUserHandler)

func AllowScopes

func AllowScopes(requiredScopes ...string) context.Handler

AllowScopes returns a middleware that validates an OAuth2 client's access token. If the token is invalid or the client does not exist, the request is halted.

This middleware handles two scenarios:

  1. Direct application sign-in: The token does not carry OAuth2 client data, so all resources are accessible without scope checks.
  2. OAuth2 client sign-in: The token embeds the client_id and scopes, which are validated to ensure the client has the necessary permissions.

Usage:

admin := app.Router("/admin", AuthInstance.VerifyHandler(), oauth2.AllowScopes("users:read", "users:write"))
admin.Get("/restricted", mainHandler)

func ClientTokenSignOptions

func ClientTokenSignOptions(clientID string, maxAge int) []jwt.SignOption

ClientTokenSignOptions returns the signing options for the client token.

func DisallowPolicies

func DisallowPolicies(policies ...Policy) context.Handler

DisallowPolicies returns a middleware that ensures an OAuth2 client's access token does not contain any of the specified resource policies. If the token contains any of the disallowed policies, the request is halted.

func DisallowScopes

func DisallowScopes(disallowedScopes ...string) context.Handler

DisallowScopes returns a middleware that ensures an OAuth2 client's access token does not contain any of the specified scopes. If the token contains any of the disallowed scopes, the request is halted.

func GenerateSharedKey

func GenerateSharedKey() (string, error)

GenerateSharedKey returns a base64-encoded (standard encoding) random 16-byte key (128-bit AES key). This is convenient for returning as JSON in an HTTP response.

func JoinScopes

func JoinScopes(scopes ...string) string

JoinScopes joins multiple scopes into a space-separated string.

func PolicyScopes

func PolicyScopes(policies ...Policy) []string

PolicyScopes converts the given policies to scopes for app clients to be registered with.

func SplitScopes

func SplitScopes(scope string) []string

SplitScopes splits a space-separated scope string into a slice.

Types

type AuthCode

type AuthCode struct {
	// Code is the short-lived authorization code string.
	Code string `pg:"type=varchar(128),primary" json:"code"`
	// CreatedAt is the timestamp of code creation.
	CreatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"created_at,omitempty"`
	// UpdatedAt is the timestamp of last code update.
	UpdatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"updated_at,omitempty"`
	// ExpiresAt is the time when the code becomes invalid.
	ExpiresAt types.ISO8601 `pg:"type=timestamp" json:"expires_at"`
	// ClientID refers to the client that requested the code.
	ClientID string `pg:"type=uuid,ref=oauth2_clients(id cascade),index" json:"client_id"`
	// UserData contains data about the authenticated user.
	UserData AuthUserData `pg:"type=jsonb" json:"user_data"`
	// State is an optional value for client tracking.
	State string `pg:"type=varchar(128)" json:"state"`
	// Scopes lists the permissions granted by the user.
	Scopes []string `pg:"type=varchar[]" json:"scopes"`
	// CodeChallenge is the PKCE S256 challenge, empty when the client did not send one.
	CodeChallenge string `json:"code_challenge,omitempty"`
	// CodeChallengeMethod is "S256" when CodeChallenge is set.
	CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
}

AuthCode holds the data for an OAuth2 authorization code.

func NewAuthCode

func NewAuthCode(clientID string, userData AuthUserData, state string, scopes []string, maxAge int) (*AuthCode, error)

NewAuthCode creates a new authorization code instance.

func (*AuthCode) HasExpired

func (a *AuthCode) HasExpired() bool

HasExpired checks if this authorization code is expired.

func (*AuthCode) URL

func (a *AuthCode) URL(redirectURI string) string

URL builds a redirect URL with the code, state, and scopes attached.

type AuthCodeStore

type AuthCodeStore interface {
	// InsertAuthCode saves a new authorization code into the store.
	InsertAuthCode(ctx context.Context, authCode *AuthCode) error
	// GetAndDeleteAuthCode retrieves and deletes the code from the store in one step.
	GetAndDeleteAuthCode(ctx context.Context, code string) (*AuthCode, bool, error)
}

AuthCodeStore describes the actions needed for storing and retrieving OAuth2 authorization codes.

func NewMemoryAuthCodeStore

func NewMemoryAuthCodeStore() AuthCodeStore

NewMemoryAuthCodeStore returns an AuthCodeStore backed by an in-memory cache.

func NewPostgresAuthCodeStore

func NewPostgresAuthCodeStore(clientsTableName, tableName string, conn PostgresConn) AuthCodeStore

NewPostgresAuthCodeStore creates a new instance of postgresAuthCodeStore using the specified clientsTableName, auth code tableName, and a PostgresConn connection. It ensures the table structure exists on initialization and returns an AuthCodeStore implementation for managing OAuth2 authorization codes.

type AuthUserData

type AuthUserData auth.User

AuthUserData is the user data that is associated with the auth code. It can be any custom data type.

type AuthorizeRequest

type AuthorizeRequest struct {
	// ClientID is the unique client identifier.
	ClientID string `json:"client_id" url:"client_id" form:"client_id"`
	// State is an optional opaque value for client tracking.
	State string `json:"state" url:"state" form:"state"`
	// Scope is the set of requested scopes, space-separated.
	Scope string `json:"scope" url:"scope" form:"scope"`
	// CodeChallenge is the optional PKCE challenge. When set, the method must be S256.
	CodeChallenge string `json:"code_challenge,omitempty" url:"code_challenge,omitempty" form:"code_challenge,omitempty"`
	// CodeChallengeMethod is the PKCE method. Only S256 is accepted.
	CodeChallengeMethod string `json:"code_challenge_method,omitempty" url:"code_challenge_method,omitempty" form:"code_challenge_method,omitempty"`
}

AuthorizeRequest holds the data submitted during authorization.

func (*AuthorizeRequest) ConsentCookieName

func (req *AuthorizeRequest) ConsentCookieName() string

ConsentCookieName returns a cookie name specific to the client ID.

func (*AuthorizeRequest) Scopes

func (req *AuthorizeRequest) Scopes() []string

Scopes parses and returns the requested scopes.

type Client

type Client struct {
	// ID is the unique identifier for the client.
	ID string `pg:"type=uuid,primary" json:"id,omitempty"`
	// CreatedAt is the timestamp when the client was created.
	CreatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"created_at,omitempty"`
	// UpdatedAt is the timestamp of the last update to the client.
	UpdatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"updated_at,omitempty"`

	// Name is the name of the client application.
	Name string `pg:"type=varchar(255),unique" json:"name"`
	// Website is the website URL of the client application.
	Website string `pg:"type=varchar(255)" json:"website"`
	// LogoURL is the URL of the client's logo.
	LogoURL string `pg:"type=varchar(255)" json:"logo_url"`
	// RedirectURI is the callback URL for the client.
	RedirectURI string `pg:"type=text" json:"redirect_uri"`
	// VerificationURI is the URL where the user should enter the user code.
	VerificationURI string `pg:"type=text,default=''" json:"verification_uri"`
	// Secret is the randomly generated secret of the client,
	// stored as-is (plaintext, it is neither encrypted nor hashed).
	// Client send it to the server to authenticate itself on every request,
	// server matches it with the stored secret to verify the client.
	Secret string `pg:"type=varchar(255)" json:"secret,omitempty"`
	// GrantTypes are the allowed grant types for the client.
	// If empty then no grant type is allowed;
	// NewClient fills it in automatically when it is not provided.
	GrantTypes []string `pg:"type=varchar[]" json:"grant_types"`

	// Scopes are the allowed scopes for the client.
	// It checks if the requested scopes are allowed by the client,
	// and passes only what is defined in the request to the actual generated token,
	// so the end-server knows what the client is allowed to do.
	Scopes []string `pg:"type=varchar[]" json:"scopes"`

	// CodeMaxAge is the maximum age for the codes, in seconds.
	// Defaults to 1 hour (3600 seconds).
	CodeMaxAge int `pg:"type=int,default=3600" json:"code_max_age"`
	// AccessMaxAge is the max age for the access tokens, in seconds. Defaults to 1 hour.
	AccessMaxAge int `pg:"type=int,default=3600" json:"access_max_age"`
	// RefreshMaxAge is the max age for the refresh tokens, in seconds. Defaults to 7 days.
	RefreshMaxAge int `pg:"type=int,default=604800" json:"refresh_max_age"`
	// Version is the version of the client. It is used as an extra claim.
	// In order to invalidate all tokens created by this client just upgrade the version.
	Version int `pg:"type=smallint,default=0" json:"version"`
}

Client represents a client application that is registered to the server. The client is the application that wants to access the user's data.

If the client is a - web application then the client is the web application itself. - mobile application then the client is the mobile application itself. - server-side application then the client is the server-side application itself.

Note that if custom ownership is required then end-developer can create a separate store/table to store the owner id and the client id from this store/table.

func GetClient

func GetClient(ctx *context.Context) (*Client, bool)

func NewClient

func NewClient(reg ClientRegistration) (*Client, error)

NewClient creates and returns a new client from reg. The client's ID and secret are generated automatically. See ClientRegistration for the required fields, the defaults and the validation.

func (*Client) AccessTokenOptions

func (c *Client) AccessTokenOptions() jwt.SignOption

AccessTokenOptions returns the signing option for the access token.

func (*Client) Claims

func (c *Client) Claims(scopes []string) ClientTokenClaims

Claims returns the client's token claims.

func (*Client) MatchGrantType

func (c *Client) MatchGrantType(grantType string) bool

MatchGrantType returns true if the client has the specific grant type.

func (*Client) MatchScopes

func (c *Client) MatchScopes(scopes []string) bool

MatchScopes returns true if the client has the specific scopes. If "scopes" is empty then it returns true, as there is nothing to check.

func (*Client) RefreshTokenOptions

func (c *Client) RefreshTokenOptions() jwt.SignOption

RefreshTokenOptions returns the signing option for the refresh token.

type ClientFilter

type ClientFilter struct {
	// Name matches the clients whose name contains this text, ignoring case.
	Name string `json:"name,omitempty"`
	// Scope matches the clients that have exactly this scope, e.g. "clients:create".
	Scope string `json:"scope,omitempty"`
	// Sort is the field to order by: "name", "created_at" or "updated_at".
	// Empty means "created_at". Any other value is an ErrInvalidClientFilter.
	Sort string `json:"sort,omitempty"`
	// SortDescending reverses the order.
	SortDescending bool `json:"sort_descending,omitzero"`
}

ClientFilter holds the optional conditions and the ordering of ListClients and CountClients. The zero value matches every client, ordered by creation time ascending.

type ClientRegistration

type ClientRegistration struct {
	// Name is the unique name of the client application. Required.
	Name string
	// Website is the website URL of the client application. Required.
	Website string
	// LogoURL is the URL of the client's logo. Required.
	LogoURL string
	// RedirectURI is the callback URL. Required when GrantTypes contains the authorization code
	// or the device code grant type.
	RedirectURI string
	// VerificationURI is the URL where the user enters the user code. Required when GrantTypes
	// contains the device code grant type.
	VerificationURI string
	// GrantTypes are the allowed grant types. When empty they are resolved from the URIs:
	// password and refresh_token always, plus authorization_code when RedirectURI is set,
	// plus the device code grant type when VerificationURI is set too.
	GrantTypes []string
	// Scopes are the allowed scopes, stored as given.
	Scopes []string
	// CodeMaxAge is the max age of the authorization and device codes, in seconds.
	// Zero or negative means 3600 (one hour).
	CodeMaxAge int
	// AccessMaxAge is the max age of the access tokens, in seconds, stored as given.
	// Zero or negative means the token does not expire.
	AccessMaxAge int
	// RefreshMaxAge is the max age of the refresh tokens, in seconds, stored as given.
	// Zero or negative means the token does not expire. When both max ages are above zero,
	// RefreshMaxAge must be at least AccessMaxAge plus 60.
	RefreshMaxAge int
}

ClientRegistration holds the values NewClient, Server.RegisterClient and Server.CreateClient build a Client from. The ID and the secret are generated.

Name, Website and LogoURL are required: an empty one makes NewClient return "name, website, logo and (redirect_uri or verification_uri) are required".

type ClientStore

type ClientStore interface {
	// InsertClient adds a new client to the store.
	InsertClient(ctx stdContext.Context, client *Client) error
	// GetClient fetches a client by its ID.
	GetClient(ctx stdContext.Context, id string) (*Client, bool, error)
	// GetClientByName fetches a client by its name.
	GetClientByName(ctx stdContext.Context, name string) (*Client, bool, error)
	// ListClients returns one page of the clients that match the filter (nil matches all)
	// and the total number of matches. Clients are returned as stored, secrets included.
	ListClients(ctx stdContext.Context, page pagination.PageOptions, filter *ClientFilter) ([]*Client, int64, error)
	// CountClients returns the number of clients that match the filter (nil matches all).
	CountClients(ctx stdContext.Context, filter *ClientFilter) (int64, error)
	// DeleteClient removes a client by its ID. It reports false when there is no such client.
	DeleteClient(ctx stdContext.Context, id string) (bool, error)
	// UpdateClientScopes replaces the scopes of a client. The secret and the version are untouched.
	// It reports false when there is no such client.
	UpdateClientScopes(ctx stdContext.Context, id string, scopes []string) (bool, error)
	// IncrementClientVersion adds one to the version of a client, which invalidates the tokens
	// issued for the previous version. The secret is untouched.
	// It reports false when there is no such client.
	IncrementClientVersion(ctx stdContext.Context, id string) (bool, error)
}

ClientStore describes methods to insert and retrieve OAuth2 clients.

func NewMemoryClientStore

func NewMemoryClientStore() ClientStore

NewMemoryClientStore creates an in-memory client store.

func NewPostgresClientStore

func NewPostgresClientStore(tableName string, conn PostgresConn) ClientStore

NewPostgresClientStore initializes a new postgresClientStore with the given table name and ensures the table is created if it doesn’t exist.

type ClientTokenClaims

type ClientTokenClaims struct {
	// ClientID is the unique ID of the client requesting the token.
	ClientID string `json:"client_id" form:"client_id" url:"client_id"`
	// ClientName is the name of the client application.
	ClientName string `json:"client_name" form:"client_name" url:"client_name"`
	// ClientWebsite is the website URL of the client application.
	ClientWebsite string `json:"client_website" form:"client_website" url:"client_website"`
	// ClientLogoURL is the URL of the client's logo.
	ClientLogoURL string `json:"client_logo_url" form:"client_logo_url" url:"client_logo_url"`
	// Scopes are the list of permissions or resources the client may access.
	Scopes []string `json:"scopes" form:"scopes" url:"scopes"`

	// ClientSecret is the client's secret key.
	// It's only available outside of oauth2 routes,
	// when the app is server-side and has rights to write to the users.
	ClientSecret string `json:"client_secret,omitempty" form:"client_secret,omitempty" url:"client_secret,omitempty"`

	// Used to verify the token's version. Useful for invalidating tokens.
	Version int `json:"version" form:"-" url:"-"`
}

ClientTokenClaims holds client-specific data embedded in tokens (e.g., client ID and scopes).

func GetClientClaims

func GetClientClaims(ctx *context.Context) (ClientTokenClaims, error)

GetClientClaims returns the token's claims of the OAuth2 client that is making the request.

func (*ClientTokenClaims) MatchPolicies

func (c *ClientTokenClaims) MatchPolicies(ctx stdContext.Context, requiredPolicies []Policy) bool

MatchPolicies reports whether the token satisfies at least one of the requiredPolicies. It returns true when requiredPolicies is empty.

type ConfirmConsentRequest

type ConfirmConsentRequest struct {
	// Decision stores the user's response: "approve" or "deny."
	Decision string `url:"decision" form:"decision"`
	// Remember indicates whether the user wants to remember this decision for future requests.
	Remember string `url:"remember" form:"remember"`

	AuthorizeRequest
}

ConfirmConsentRequest is the form data submitted by the user on the consent page.

func (*ConfirmConsentRequest) Approved

func (req *ConfirmConsentRequest) Approved() bool

Approved returns true if the user decided to approve the requested scopes.

func (*ConfirmConsentRequest) ShouldRemember

func (req *ConfirmConsentRequest) ShouldRemember() bool

ShouldRemember returns true if the user wants to remember the consent decision.

type DeviceCode

type DeviceCode struct {
	// Code is the unique device code that the client will use to request a token.
	Code string `pg:"type=varchar(128),primary" json:"code"`
	// CreatedAt indicates when the code was generated.
	CreatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"created_at,omitempty"`
	// UpdatedAt is the timestamp of last code update.
	UpdatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"updated_at,omitempty"`
	// ExpiresAt is the time at which the device code will no longer be valid.
	ExpiresAt types.ISO8601 `pg:"type=timestamp" json:"expires_at"`
	// ClientID is the ID of the client requesting the device code.
	ClientID string `pg:"type=uuid,ref=oauth2_clients(id cascade),index" json:"client_id"`
	// UserData contains the authenticated user’s data.
	UserData AuthUserData `pg:"type=jsonb" json:"user_data"`
	// UserCode is the code displayed to the user, who must enter it on the verification URI.
	UserCode string `pg:"type=varchar(128)" json:"user_code"`
	// Scopes lists the permissions requested by the client.
	Scopes []string `pg:"type=varchar[]" json:"scopes"`
	// Interval is the polling interval in seconds for the client to check the device code.
	Interval int `pg:"type=int,default=0" json:"interval,omitzero"`
}

DeviceCode holds information for the device code flow authorization.

func NewDeviceCode

func NewDeviceCode(clientID string, userData AuthUserData, interval int, scopes []string, maxAge int) (*DeviceCode, error)

NewDeviceCode creates and initializes a new DeviceCode with a unique device code and user code, to be used in the OAuth2 device flow.

func (*DeviceCode) AuthResponse

func (d *DeviceCode) AuthResponse(verificationURI string) oauth2.DeviceAuthResponse

AuthResponse constructs and returns a device authorization response that includes the user code and verification URIs.

func (*DeviceCode) HasExpired

func (d *DeviceCode) HasExpired() bool

HasExpired returns true if the current time is after the code’s ExpiresAt.

type DeviceCodeStore

type DeviceCodeStore interface {
	// InsertDeviceCode saves a device code entry in the store.
	InsertDeviceCode(ctx stdContext.Context, device *DeviceCode) error
	// GetAndDeleteDeviceCode retrieves and deletes a device code by its code value.
	GetAndDeleteDeviceCode(ctx stdContext.Context, code string) (*DeviceCode, bool, error)
	// GetDeviceCodeByUserCode retrieves a device code using the user code field.
	GetDeviceCodeByUserCode(ctx stdContext.Context, userCode string) (*DeviceCode, bool, error)
}

DeviceCodeStore defines methods to persist device codes and retrieve them by code or user code.

func NewMemoryDeviceCodeStore

func NewMemoryDeviceCodeStore() DeviceCodeStore

NewMemoryDeviceCodeStore creates an in-memory device code store.

func NewPostgresDeviceCodeStore

func NewPostgresDeviceCodeStore(clientsTableName, tableName string, conn PostgresConn) DeviceCodeStore

NewPostgresDeviceCodeStore creates a new postgresDeviceCodeStore instance and ensures the associated table is created if it doesn't exist.

type Option

type Option func(*serverOptions)

Option is a function that configures the server.

func WithAuthCodeStore

func WithAuthCodeStore(authCodeStore AuthCodeStore) Option

WithAuthCodeStore sets the authorization code store for the server.

func WithClientStore

func WithClientStore(clientStore ClientStore) Option

WithClientStore sets the client store for the server.

func WithConsentPageURL

func WithConsentPageURL(consentPageURL string) Option

WithConsentPageURL sets the consent page URL for the server.

func WithDeviceCodeStore

func WithDeviceCodeStore(deviceCodeStore DeviceCodeStore) Option

WithDeviceCodeStore sets the device code store for the server.

func WithDeviceInterval

func WithDeviceInterval(intervalSeconds int) Option

WithDeviceInterval sets the default polling interval for device code confirmation.

func WithLoginPageURL

func WithLoginPageURL(loginPageURL string) Option

WithLoginPageURL sets the login page URL for the server.

type Policy

type Policy interface {

	// Matches checks if the policy matches the given claims.
	Matches(ctx stdContext.Context, claims *ClientTokenClaims) bool
}

Policy is an interface that all policy types must implement.

func NewScopePolicies

func NewScopePolicies(scopes ...string) []Policy

NewScopePolicies creates a new slice of string scope policies.

func WrapPolicies

func WrapPolicies(policies ...Policy) Policy

WrapPolicies wraps the given policies into a single policy. Example:

policies := append(oauth2.NewScopePolicies("users:read", "users:write"),
	oauth2.ResourcePolicy{Resource: "orders", Action: "read"},
)
policy := oauth2.WrapPolicies(policies...)
app.Get("/protected", oauth2.AllowPolicies(policy), handler)

type PostgresConn

type PostgresConn interface {
	// Exec executes a query that doesn't return rows.
	Exec(ctx stdContext.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
	// QueryRow executes a query that is expected to return at most one row.
	QueryRow(ctx stdContext.Context, sql string, arguments ...any) pgx.Row
	// Query executes a query that returns rows.
	Query(ctx stdContext.Context, sql string, args ...any) (pgx.Rows, error)
}

PostgresConn is an interface that defines the methods required to interact with a PostgreSQL database (pool connection).

type ResourcePolicy

type ResourcePolicy struct {
	Resource string `json:"resource" yaml:"Resource"`
	Action   string `json:"action" yaml:"Action"` // more can be added by separating them with a space.
}

ResourcePolicy represents a fine-grained rule for a given resource/action. For example, Resource="users" and Action="read" => "users:read" scope.

A policy of {Resource: "users", Action: "create read update delete"}} generates the following scopes: "users:create", "users:read", "users:update", "users:delete".

func (ResourcePolicy) Actions

func (rp ResourcePolicy) Actions() []string

Actions returns just the actions.

func (ResourcePolicy) Matches

func (rp ResourcePolicy) Matches(_ stdContext.Context, claims *ClientTokenClaims) bool

Matches checks if a scope string matches the resource:action requirement. For instance, a scope "invoices:read" means resource="invoices", action="read". If more than one Action is provided (separated by space), at least one of them must match. If Actions is empty, then all scopes that match the resource are accepted.

func (ResourcePolicy) Scopes

func (rp ResourcePolicy) Scopes() []string

Scopes returns the resource:action scope strings.

func (ResourcePolicy) String

func (rp ResourcePolicy) String() string

String returns the resource:action scope string.

type ScopePolicy

type ScopePolicy struct {
	Scope string `json:"scope" yaml:"Scope"`
}

ScopePolicy represents a simple string-based scope policy.

func (ScopePolicy) Matches

func (p ScopePolicy) Matches(_ stdContext.Context, claims *ClientTokenClaims) bool

Matches checks if the given scope matches the policy's scope.

func (ScopePolicy) String

func (p ScopePolicy) String() string

String returns the scope as a string.

type Server

type Server[UserData AuthUserData] struct {
	// Auth is the Iris Auth instance used for user authentication and verification.
	Auth *auth.Auth[UserData]
	// contains filtered or unexported fields
}

Server defines an OAuth2 server capable of handling various grant types and flows.

Usage:

type User struct {
	ID        string `json:"id"`
	// Add any other fields you need.
}

oauth2Server := oauth2.New[User](s,
	oauth2.WithClientStore(oauth2.NewMemoryClientStore()),
	oauth2.WithAuthCodeStore(oauth2.NewMemoryAuthCodeStore()),
	oauth2.WithDeviceCodeStore(oauth2.NewMemoryDeviceCodeStore()),
	oauth2.WithLoginPageURL("/signin"),
	oauth2.WithConsentPageURL("/oauth2/consent"),
)

app.Router("/oauth2", oauth2Server)

- GET /authorize: the authorization endpoint. - GET /consent: the built-in consent page, if the ConsentPageURL is "default" or matches the *relpath*/consent endpoint. - POST /consent: the confirmation endpoint, if the ConsentPageURL is not empty. - GET /consent/revoke: the revoke consent endpoint, if the ConsentPageURL is not empty. - POST /device/code: the device code endpoint. - POST /token: the token endpoint. - POST /token/introspect: the token introspection endpoint.

func New

func New[UserData AuthUserData](a *auth.Auth[UserData], opts ...Option) *Server[UserData]

New creates a new OAuth2 server with the given Auth instance and options. If the Auth instance is not provided, it will try to resolve it using the auth.Resolve function. The server will be built with the provided options.

It can be registered as a router, as it implements the router.Router's Routing method, e.g. app.Router("/oauth2", server).

func (*Server[UserData]) AuthorizeHandler

func (s *Server[UserData]) AuthorizeHandler() context.Handler

AuthorizeHandler returns the handler for the authorization endpoint. If ConsentPageURL is set, it returns the consent handler; otherwise, it returns the auth code handler.

func (*Server[UserData]) ClientStore

func (s *Server[UserData]) ClientStore() ClientStore

ClientStore returns the client store the server was configured with.

func (*Server[UserData]) ClientVerifier

func (s *Server[UserData]) ClientVerifier() auth.VerifyUserFunc[ClientTokenClaims]

ClientVerifier returns a VerifyUserFunc that verifies the full client (auth) claims.

func (*Server[UserData]) ConfirmConsentHandler

func (s *Server[UserData]) ConfirmConsentHandler() context.Handler

ConfirmConsentHandler returns the handler for confirming user consent.

func (*Server[UserData]) CreateClient

func (s *Server[UserData]) CreateClient(ctx stdContext.Context, reg ClientRegistration) (*Client, error)

CreateClient creates a new client from reg and inserts it into the client store. Unlike RegisterClient it never returns an existing client: it returns ErrClientAlreadyExists when the name is taken.

func (*Server[UserData]) DefaultConsentPageHandler

func (s *Server[UserData]) DefaultConsentPageHandler() context.Handler

DefaultConsentPageHandler returns the default consent page handler.

func (*Server[UserData]) DeviceCodeHandler

func (s *Server[UserData]) DeviceCodeHandler() context.Handler

DeviceCodeHandler returns the handler for the device code endpoint.

func (*Server[UserData]) EnsureClientScopes

func (s *Server[UserData]) EnsureClientScopes(ctx stdContext.Context, client *Client, scopes []string) (bool, error)

EnsureClientScopes adds to the stored client the scopes it lacks (a union that keeps the existing order and removes nothing) and updates client.Scopes to match. The secret and the version are untouched, so every token already issued for the client stays valid. It reports false, with a nil error, when nothing was missing.

func (*Server[UserData]) RegisterClient

func (s *Server[UserData]) RegisterClient(ctx stdContext.Context, reg ClientRegistration) (*Client, error)

RegisterClient creates a new client from reg and inserts it into the configured client store, unless a client with the same name already exists, in which case it returns that one unchanged. See ClientRegistration for the required fields and the defaults.

func (*Server[UserData]) RevokeConsentHandler

func (s *Server[UserData]) RevokeConsentHandler() context.Handler

RevokeConsentHandler returns the handler for revoking user consent.

func (*Server[UserData]) Routing

func (s *Server[UserData]) Routing(r router.Router)

Routing registers the necessary routes for the OAuth2 server. - GET /authorize: the authorization endpoint. - GET /consent: the built-in consent page, if the ConsentPageURL is "default" or matches the *relpath*/consent endpoint. - POST /consent: the confirmation endpoint, if the ConsentPageURL is not empty. - GET /consent/revoke: the revoke consent endpoint, if the ConsentPageURL is not empty. - POST /device/code: the device code endpoint. - POST /token: the token endpoint. - POST /token/introspect: the token introspection endpoint.

func (*Server[UserData]) SignToken

func (s *Server[UserData]) SignToken(clientID string, accessMaxAge, refreshMaxAge int, claims ...any) (*oauth2.Token, error)

SignToken signs a token with the given client ID, max age (seconds) and one or more claims.

func (*Server[UserData]) TokenHandler

func (s *Server[UserData]) TokenHandler() context.Handler

TokenHandler returns the handler for the token endpoint.

func (*Server[UserData]) TokenIntrospectHandler

func (s *Server[UserData]) TokenIntrospectHandler() context.Handler

TokenIntrospectHandler returns the handler for the token introspection endpoint.

type Token

type Token = oauth2.Token

Token is an alias of the oauth2.Token type.

Directories

Path Synopsis
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the stack.
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the stack.

Jump to

Keyboard shortcuts

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