oidcauth

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2022 License: Apache-2.0 Imports: 13 Imported by: 0

README

oidcauth - OIDC Client Authentication for Gin-Gonic

Build Status codecov Go Report Card GoDoc

Usage

Download and install it:

go get github.com/TJM/gin-gonic-oidcauth

Import it in your code:

import oidcauth "github.com/TJM/gin-gonic-oidcauth"

Use it: (see complete examples)

  // NOTE: oidcauth *requires* sessions *before* oidcauth
  // SEE Examples to see how.

	// Authentication Config
	auth, err := oidcauth.GetOidcAuth(oidcauth.DefaultConfig())
	if err != nil {
		panic("auth setup failed")
	}
	router.GET("/login", auth.Login) // Unnecessary, as requesting a "AuthRequired" resource will initiate login, but potentially convenient
	router.GET("/callback", auth.AuthCallback)
  router.GET("/logout", auth.Logout)

  // Private Route Group...
	private := r.Group("/private", auth.AuthRequired())
	{
		private.GET("", func(c *gin.Context) {
      c.String(http.StatusOK, "Private!")
    }
    // ...
  }

Examples

Prerequisites:

  • Oauth2 Identity Provider (IdP) service that supports OIDC
    • You can use something like DEX to test with.
    • Alternatively, you could also use something like:
DEX Identity Provider

The example below will use DEX IdP. Please clone their repo and start DEX in a separate window.

  • Start DEX IdP:
./bin/dex serve examples/config-dev.yaml
  • Start [DEX ExampleApp(example/dex/main.go)]:
go run example/dex/main.go
Google Accounts Identity Provider

The example below will use Google Accounts. See: go-oidc examples readme.

NOTE: This example used port 5556 to be compatible with the other go-oidc examples, but it will clash with "dex" which runs on the same port by default.

  • Setup Google

    1. Visit your Google Developer Console.
    2. Click "Credentials" on the left column.
    3. Click the "Create credentials" button followed by "OAuth client ID".
    4. Select "Web application" and add "http://127.0.0.1:5556/auth/google/callback" as an authorized redirect URI.
    5. Click create and add the printed client ID and secret to your environment using the following variables:
    export GOOGLE_OAUTH2_CLIENT_ID=
    export GOOGLE_OAUTH2_CLIENT_SECRET=
    
  • Start Google Example example/google/main.go:

go run example/google/main.go

License

Licensed under the Apache License, Version 2.0.

Documentation

Index

Constants

View Source
const (

	// AuthUserKey stores the authenticated user's login (username or email) in this context key
	AuthUserKey string = "user"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// ClientID is the OAUTH2 Client ID
	// Default value is: (read from OS ENV: OAUTH2_CLIENT_ID)
	ClientID string

	// ClientSecret is the OAUTH2 Client Secret
	// Default value is: (read from OS ENV: OAUTH2_CLIENT_SECRET)
	ClientSecret string

	// IssuerURL is the root URL to theIdentity Provider
	// Default value is: (read from OS ENV: OIDC_ISSUER_URL)
	IssuerURL string

	// RedirectURL is the path that the Identity Provider will redirect clients to
	// Default value is: (read from OS ENV: OIDC_REDIRECT_URL)
	RedirectURL string

	// Scopes is a list of OIDC Scopes to request.
	// Default value is: []string{oidc.ScopeOpenID, "profile", "email"}
	Scopes []string

	// LoginClaim is the OIDC claim to map to the user's login (username)
	// Default value is: "email"
	LoginClaim string

	// SessionClaims is the list of OIDC claims to add to the user's session (in addition to LoginClaim)
	// Example []string{"email", "givenName", "name"}
	// NOTE: This can be set to ["*"] to load *all* claims. (nonce will be excluded)
	// Default value is: ["*"]
	SessionClaims []string

	// SessionPrefix is an optional prefix string to prefix to the claims (i.e. google: or corp:) to prevent
	// clashes in the session namespace
	// Default value is: ""
	SessionPrefix string

	// DefaultAuthenticatedURL is the URL to redirect a user to after successful authentication. By default, we will
	//   try to determine where they were when they requested to login and send them back there.
	// Default value is: "/"
	DefaultAuthenticatedURL string

	// LogoutURL is the URL to redirect a user to after logging out.
	// NOTE: If you require / to be authenticated, setting this to / will start the login process immediately, which may not be desirable.
	// Default value is: "/"
	LogoutURL string

	UserFromLoginClaim func(loginClaim string) (interface{}, error)

	AuthCallback func(loginClaim string, claim map[string]interface{}) error
}

Config represents available options for oidcauth.

func DefaultConfig

func DefaultConfig() (c *Config)

DefaultConfig will create a new config object with defaults NOTE: This matches the examples on https://github.com/coreos/go-oidc/tree/v3/example

func ExampleConfigDex

func ExampleConfigDex() (c *Config)

ExampleConfigDex will return the config for a default DEX IdP example-app DEX: https://github.com/dexidp/dex

func ExampleConfigGoogle

func ExampleConfigGoogle() (c *Config)

ExampleConfigGoogle will return the config for the Google Accounts IdP like the go-oidc examples go-oidc google example: https://github.com/coreos/go-oidc/tree/v3/example

func (*Config) GetOidcAuth

func (c *Config) GetOidcAuth() (o *OidcAuth, err error)

GetOidcAuth returns the configured OIDC authentication controller

func (Config) Validate

func (c Config) Validate() (err error)

Validate will validate the Config

type OidcAuth

type OidcAuth struct {
	Debug bool // DUMP oidc paramters as JSON instead of redirecting
	// contains filtered or unexported fields
}

OidcAuth handles OIDC Authentication

func GetOidcAuth

func GetOidcAuth(c *Config) (o *OidcAuth, err error)

GetOidcAuth returns the configured OIDC authentication controller

func (*OidcAuth) AuthCallback

func (o *OidcAuth) AuthCallback(c *gin.Context)

AuthCallback will handle the authentication callback (redirect) from the Identity Provider

This is the part that actually "does" the authentication.

func (*OidcAuth) AuthRequired

func (o *OidcAuth) AuthRequired() gin.HandlerFunc

AuthRequired middleware requires OIDC authentication BE CAREFUL Adding this to / (or the top level router)

func (*OidcAuth) Login

func (o *OidcAuth) Login(c *gin.Context)

Login will setup the appropriate state and redirect the user to the authentication provider

func (*OidcAuth) Logout

func (o *OidcAuth) Logout(c *gin.Context)

Logout will clear the session NOTE: It will not invalidate the OIDC session (Not SSO)

Directories

Path Synopsis
example
dex

Jump to

Keyboard shortcuts

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