oidcauth

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2021 License: Apache-2.0 Imports: 12 Imported by: 1

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"

Example

Prerequisites:

  • Identity Provider (IdP) Server that supports OIDC - You can use something like DEX to test with. Alternatively, you could also use Google Accounts, GitHub accounts, etc. The examples below will use Google Accounts. See: go-oidc examples readme

  • Sessions example: example/main.go

package main

import (
	"fmt"
	"net/http"
	"os"

	oidcauth "github.com/TJM/gin-gonic-oidcauth"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	// Session Config (Basic cookies)
	store := cookie.NewStore([]byte("secret"), nil) // Do not use "secret", nil in production. This sets the keypairs for auth, encryption of the cookies.
	r.Use(sessions.Sessions("mysession", store))    // Sessions must be Use(d) before oidcauth, as oidcauth requires sessions

	// NOTE: DefaultConfig uses Google Accounts
	// - See https://github.com/coreos/go-oidc/blob/v3/example/README.md
	auth, err := oidcauth.GetOidcAuth(oidcauth.DefaultConfig())
	if err != nil {
		panic("auth setup failed")
	}
	if os.Getenv("DEBUG") != "" {
		auth.Debug = true
	}

	r.GET("/login", auth.Login) // Unnecessary, as requesting a "AuthRequired" resource will initiate login, but potentially convenient
	r.GET("/auth/google/callback", auth.AuthCallback)
	r.GET("/logout", auth.Logout)

	// Allow access to / for unauthenticated users, but authenticated users will be greated by name.
	r.GET("/", func(c *gin.Context) {
		session := sessions.Default(c)
		name := "world"
		n := session.Get("name")
		if n != nil {
			name = n.(string)
		}
		// session.Save() // if it has been changed, which it has not
		c.String(http.StatusOK, fmt.Sprintf("Hello, %s.", name))
	})

	private := r.Group("/private", auth.AuthRequired())
	{
		private.GET("", func(c *gin.Context) {
			var name, email, out string
			login := c.GetString(oidcauth.AuthUserKey)
			session := sessions.Default(c)
			n := session.Get("name")
			if n == nil {
				name = "Someone without a name?"
			} else {
				name = n.(string)
			}
			e := session.Get("email")
			if e != nil {
				email = e.(string)
			}
			out = fmt.Sprintf("Hello, %s <%s>.\nLogin: %s\n", name, email, login)
			// session.Save() // if it has been changed, which it has not
			c.String(http.StatusOK, out)
			return
		})
	}

	r.Run(":5556")
}

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: "https://accounts.google.com"
	IssuerURL string

	// RedirectURL is the path that the Identity Provider will redirect clients to
	// Default value is: "http://127.0.0.1:5556/auth/google/callback"
	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
}

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 (*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

Jump to

Keyboard shortcuts

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