oauth2

package
v1.0.32 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

README

README

The auth/oauth2 package is used by Go services to apply OAuth2 authentication.

OAuth2 Providers

authentik

authentik is an open-source identity and access management solution that supports OAuth2. The authentik OAuth2 provider is used to authenticate users and authorize access to services.

To use the authentik OAuth2 provider, you first need to set up an authentik server, create and OAuth2 Provider and create an Application through their UI.

The client ID, client secret are required to configure the authentik OAuth2 provider.

Following is an example of how to use the auth/oauth2 package to authenticate users using the authentik OAuth2 provider.

package main

import (
	goOauth2 "golang.org/x/oauth2"
	"net/http"

	"github.com/labstack/echo/v4"
	
	"github.com/IOTechSystems/go-mod-edge-utils/pkg/auth/jwt"
	"github.com/IOTechSystems/go-mod-edge-utils/pkg/auth/oauth2"
	"github.com/IOTechSystems/go-mod-edge-utils/pkg/errors"
	"github.com/IOTechSystems/go-mod-edge-utils/pkg/log"
)

const (
	clientID     = "Your client ID"
	clientSecret = "Your client secret"
	// The redirect URL should be the same as the callback URL in your application
	redirectURL  = "http://localhost:8080/callback"
	
	// The following URLs are the authentik OAuth2 provider URLs whose domain should be replaced with your authentik server domain
	authURL      = "http://localhost:9000/application/o/authorize/"
	tokenURL     = "http://localhost:9000/application/o/token/"
	userInfoURL  = "http://localhost:9000/application/o/userinfo/"
	redirectPath = "/"
)

func main() {
	e := echo.New()

	// Set up the OAuth2 configuration for authentik
	config := oauth2.NewAuthentikConfigs(clientID, clientSecret, authURL, tokenURL, redirectURL, userInfoURL, redirectPath)

	logger := log.InitLogger("main", log.InfoLog, nil)

	// Create the authentik OAuth2 authenticator
	oauth2Authenticator := oauth2.NewAuthentikAuthenticator(config, logger)

	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})
	// Set up the login and callback routes
	e.GET("/login", echo.WrapHandler(oauth2Authenticator.RequestAuth()))
	e.GET("/callback", echo.WrapHandler(oauth2Authenticator.Callback(handleUserInfo)))
	e.Logger.Fatal(e.Start(":8080"))
}

// handleUserInfo is a callback function that is called after the user is authenticated from the OAuth2 provider.
func handleUserInfo(userInfo any) (token *jwt.TokenDetails, err errors.Error) {
	userInfo, ok := userInfo.(oauth2.AuthentikUserInfo)
	if !ok {
		return nil, errors.NewBaseError(errors.KindServerError, "failed to cast user info to AuthentikUserInfo", nil, nil)
	}

	fakeToken := &jwt.TokenDetails{
		AccessToken:  "accesstoken",
		RefreshToken: "refreshtoken",
		AccessId:     "accessid",
		RefreshId:    "refreshid",
		AtExpires:    0,
		RtExpires:    0,
	}
	return fakeToken, nil
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Authenticator

type Authenticator interface {
	// RequestAuth returns a http.HandlerFunc that redirects the user to the OAuth2 provider for authentication and gets the authorization code.
	RequestAuth() http.HandlerFunc
	// Callback returns a http.HandlerFunc that exchanges the authorization code for an access token and fetches user info from the OAuth2 provider.
	// The parameter is a function that takes the user info and returns the JWT token or an error.
	Callback(func(userInfo any) (token *jwt.TokenDetails, err errors.Error)) http.HandlerFunc
	// GetTokenByUserID returns the cache token by user ID.
	GetTokenByUserID(userId string) (*oauth2.Token, errors.Error)
}

Authenticator is an interface for OAuth2 authenticators.

func NewAuthentikAuthenticator

func NewAuthentikAuthenticator(config Config, lc log.Logger) Authenticator

NewAuthentikAuthenticator creates a new Authenticator for authentik.

type AuthentikAuthenticator

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

func (*AuthentikAuthenticator) Callback

func (a *AuthentikAuthenticator) Callback(loginAndGetJWT func(userInfo any) (token *jwt.TokenDetails, err errors.Error)) http.HandlerFunc

Callback returns a http.HandlerFunc that exchanges the authorization code for an access token and fetches user info from the OAuth2 provider. The parameter is a function that takes the user info and returns the JWT token or an error.

func (*AuthentikAuthenticator) GetTokenByUserID added in v1.0.26

func (a *AuthentikAuthenticator) GetTokenByUserID(userId string) (*oauth2.Token, errors.Error)

GetTokenByUserID returns the oauth2 token by user ID

func (*AuthentikAuthenticator) RequestAuth

func (a *AuthentikAuthenticator) RequestAuth() http.HandlerFunc

RequestAuth returns a http.HandlerFunc that redirects the user to the OAuth2 provider for authentication.

type AuthentikUserInfo

type AuthentikUserInfo struct {
	Sub               string   `json:"sub"`
	Email             string   `json:"email"`
	VerifiedEmail     bool     `json:"email_verified"`
	Name              string   `json:"name"`
	GivenName         string   `json:"given_name"`
	PreferredUsername string   `json:"preferred_username"`
	Nickname          string   `json:"nickname"`
	Groups            []string `json:"groups"`

	// Custom fields of a more common name for the user ID
	ID string `json:"id"`
}

func (*AuthentikUserInfo) Validate

func (u *AuthentikUserInfo) Validate() error

Validate validates user info

type Config added in v1.0.24

type Config struct {
	GoOAuth2Config *oauth2.Config
	UserInfoURL    string
	RedirectPath   string // RedirectPath is the path that the user will be redirected to after login
}

func NewAuthentikConfigs

func NewAuthentikConfigs(clientId, clientSecret, authURL, tokenURL, redirectURL, userInfoURL, redirectPath string) Config

NewAuthentikConfigs returns a new Config for authentik.

func NewGitHubConfigs added in v1.0.28

func NewGitHubConfigs(clientId, clientSecret, redirectURL, redirectPath string) Config

NewGitHubConfigs returns a new Config for GitHub.

func NewGoogleConfigs added in v1.0.28

func NewGoogleConfigs(clientId, clientSecret, redirectURL, redirectPath string) Config

NewGoogleConfigs returns a new Config for Google.

type GitHubAuthenticator added in v1.0.28

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

func NewGitHubAuthenticator added in v1.0.28

func NewGitHubAuthenticator(config Config, lc log.Logger) *GitHubAuthenticator

func (*GitHubAuthenticator) Callback added in v1.0.28

func (g *GitHubAuthenticator) Callback(loginAndGetJWT func(userInfo any) (token *jwt.TokenDetails, err errors.Error)) http.HandlerFunc

Callback returns a http.HandlerFunc that exchanges the authorization code for an access token and fetches user info from the OAuth2 provider. The parameter is a function that takes the user info and returns the JWT token or an error.

func (*GitHubAuthenticator) GetTokenByUserID added in v1.0.28

func (g *GitHubAuthenticator) GetTokenByUserID(userId string) (*oauth2.Token, errors.Error)

GetTokenByUserID returns the oauth2 token by user ID

func (*GitHubAuthenticator) RequestAuth added in v1.0.28

func (g *GitHubAuthenticator) RequestAuth() http.HandlerFunc

RequestAuth returns a http.HandlerFunc that redirects the user to the OAuth2 provider for authentication.

type GitHubUserInfo added in v1.0.28

type GitHubUserInfo struct {
	ID    int64  `json:"id"`
	Email string `json:"email"`
	Name  string `json:"name"`
}

type GoogleAuthenticator added in v1.0.28

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

func NewGoogleAuthenticator added in v1.0.28

func NewGoogleAuthenticator(config Config, lc log.Logger) *GoogleAuthenticator

func (*GoogleAuthenticator) Callback added in v1.0.28

func (g *GoogleAuthenticator) Callback(loginAndGetJWT func(userInfo any) (token *jwt.TokenDetails, err errors.Error)) http.HandlerFunc

Callback returns a http.HandlerFunc that exchanges the authorization code for an access token and fetches user info from the OAuth2 provider. The parameter is a function that takes the user info and returns the JWT token or an error.

func (*GoogleAuthenticator) GetTokenByUserID added in v1.0.28

func (g *GoogleAuthenticator) GetTokenByUserID(userId string) (*oauth2.Token, errors.Error)

GetTokenByUserID returns the oauth2 token by user ID

func (*GoogleAuthenticator) RequestAuth added in v1.0.28

func (g *GoogleAuthenticator) RequestAuth() http.HandlerFunc

RequestAuth returns a http.HandlerFunc that redirects the user to the OAuth2 provider for authentication.

type GoogleUserInfo added in v1.0.28

type GoogleUserInfo struct {
	ID            string `json:"id"`
	Email         string `json:"email"`
	VerifiedEmail bool   `json:"verified_email"`
	Name          string `json:"name"`
	GivenName     string `json:"given_name"`
	FamilyName    string `json:"family_name"`
	Picture       string `json:"picture"`
	Locale        string `json:"locale"`
	HostedDomain  string `json:"hd"`
}

func (*GoogleUserInfo) Validate added in v1.0.28

func (u *GoogleUserInfo) Validate() error

Validate validates user info

type Provider added in v1.0.28

type Provider string
const (
	Authentik Provider = "authentik"
	Google    Provider = "google"
	GitHub    Provider = "github"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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