goauth

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2024 License: MIT Imports: 6 Imported by: 0

README

goauth

Go Reference Go Report Card

A comprehensive Go package that provides a unified interface for OAuth2 authentication across multiple providers. This package simplifies the integration of OAuth2 authentication in your Go applications by offering a consistent API for various OAuth2 providers.

Features

  • Unified interface for all OAuth2 providers
  • Easy-to-use API
  • Type-safe implementation
  • Extensive provider support
  • Built-in token management
  • Standardized user information
  • Customizable scopes
  • Error handling
  • Token refresh support

Installation

go get -u github.com/mstgnz/goauth

Quick Start

Here's a simple example using GitHub OAuth2:

package main

import (
    "log"
    "net/http"
    "github.com/mstgnz/goauth/initialize"
    "golang.org/x/oauth2"
)

func main() {
    // Initialize the provider
    provider, err := initialize.NewProviderByName("github")
    if err != nil {
        log.Fatal(err)
    }

    // Configure the provider
    provider.SetClientId("your-client-id")
    provider.SetClientSecret("your-client-secret")
    provider.SetRedirectUrl("http://localhost:8080/callback")
    provider.SetScopes([]string{"read:user", "user:email"})

    // Setup login handler
    http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
        url := provider.BuildAuthUrl("state", oauth2.AccessTypeOffline)
        http.Redirect(w, r, url, http.StatusTemporaryRedirect)
    })

    // Setup callback handler
    http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
        // Exchange code for token
        token, err := provider.FetchToken(r.URL.Query().Get("code"))
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        // Get user information
        user, err := provider.FetchUser(token)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        log.Printf("Logged in user: %+v", user)
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

Supported Providers

The package currently supports the following OAuth2 providers:

Provider Documentation
Apple Apple Developer
Discord Discord Developer
Facebook Facebook for Developers
Gitea Gitea Developer
Gitee Gitee Developer
GitHub GitHub Developer
GitLab GitLab Developer
Google Google Identity Platform
Instagram Instagram Graph API
Kakao Kakao Developers
LiveChat LiveChat API
Mailcow Mailcow API
Microsoft Microsoft Identity Platform
OIDC OpenID Connect
Patreon Patreon API
Spotify Spotify for Developers
Strava Strava API
Twitch Twitch Developers
X (Twitter) X Developer
VK VK API
Yandex Yandex Passport API

Advanced Usage

Custom Scopes
provider.SetScopes([]string{
    "read:user",
    "user:email",
    "custom:scope",
})
Token Refresh
newToken, err := provider.RefreshToken(oldToken)
if err != nil {
    log.Fatal(err)
}
Custom HTTP Client
client := provider.Client(token)
resp, err := client.Get("https://api.provider.com/endpoint")

Best Practices

  1. Environment Variables: Store sensitive credentials in environment variables

    provider.SetClientId(os.Getenv("OAUTH_CLIENT_ID"))
    provider.SetClientSecret(os.Getenv("OAUTH_CLIENT_SECRET"))
    
  2. State Parameter: Always validate the state parameter

    if r.URL.Query().Get("state") != expectedState {
        http.Error(w, "Invalid state parameter", http.StatusBadRequest)
        return
    }
    
  3. Error Handling: Implement proper error handling

    if err := provider.ValidateConfig(); err != nil {
        log.Fatal("Configuration error:", err)
    }
    

Security Considerations

  • Always use HTTPS in production
  • Implement CSRF protection using the state parameter
  • Store tokens securely
  • Use environment variables for credentials
  • Implement PKCE when available
  • Keep scopes to minimum required
  • Properly handle token expiration and refresh

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

If you encounter any issues or have questions, please file an issue on the GitHub repository.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseProvider

type BaseProvider struct{}

provider.BaseProvider implements common functionality for all providers

func (*BaseProvider) RefreshTokenNotSupported

func (b *BaseProvider) RefreshTokenNotSupported() (*oauth2.Token, error)

RefreshTokenNotSupported returns a standard error for providers that don't support token refresh.

func (*BaseProvider) ValidateConfig

func (b *BaseProvider) ValidateConfig(clientId, clientSecret, redirectUrl string) error

ValidateConfig implements the common validation logic for all providers.

type Credential

type Credential struct {
	Id           string         `json:"id"`
	Name         string         `json:"name"`
	Username     string         `json:"username"`
	Email        string         `json:"email"`
	AvatarUrl    string         `json:"avatarUrl"`
	AccessToken  string         `json:"accessToken"`
	RefreshToken string         `json:"refreshToken"`
	Expiry       string         `json:"expiry"`
	RawUser      map[string]any `json:"rawUser"`
}

Credential defines a standardized OAuth2 user data structure. It represents the information retrieved from the OAuth2 provider's user API.

type OAuth2Config

type OAuth2Config struct {
	Ctx          context.Context // Context for the provider operations.
	DisplayName  string          // Human-readable name of the OAuth2 provider.
	ClientId     string          // Client ID associated with the OAuth2 provider.
	ClientSecret string          // Client secret associated with the OAuth2 provider.
	RedirectUrl  string          // Redirect URL to complete the OAuth2 flow.
	AuthUrl      string          // URL for the OAuth2 authorization service.
	TokenUrl     string          // URL for the OAuth2 token exchange service.
	UserApiUrl   string          // URL for fetching user information from the provider.
	Scopes       []string        // Requested access permissions from the provider.
	Pkce         bool            // Indicates whether the provider supports the PKCE flow.
	TeamID       string          // Team ID for Apple Sign In.
}

OAuth2Config encapsulates common attributes and behaviors shared among OAuth2 providers. It serves as a foundation for creating specific provider implementations.

func (*OAuth2Config) BuildAuthUrl

func (oc *OAuth2Config) BuildAuthUrl(state string, opts ...oauth2.AuthCodeOption) string

BuildAuthUrl returns a URL to the OAuth2 provider's consent page that asks for permissions explicitly. It implements the BuildAuthUrl() method of the Provider interface. The state parameter is a unique value to prevent CSRF attacks during the OAuth2 flow.

func (*OAuth2Config) Client

func (oc *OAuth2Config) Client(token *oauth2.Token) *http.Client

Client returns an HTTP client using the provided OAuth2 token. It implements the Client() method of the Provider interface. The client is configured to include the OAuth2 token in its requests.

func (*OAuth2Config) FetchRawData

func (oc *OAuth2Config) FetchRawData(token *oauth2.Token) ([]byte, error)

FetchRawData requests and marshals the OAuth user API response. It implements the FetchRawData() method of the Provider interface. The user API response contains detailed information about the authenticated user.

func (*OAuth2Config) FetchToken

func (oc *OAuth2Config) FetchToken(code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)

FetchToken converts an authorization code to an OAuth2 token. It implements the FetchToken() method of the Provider interface. This step is performed after the user grants permission in the OAuth2 flow.

func (*OAuth2Config) GetAuthUrl

func (oc *OAuth2Config) GetAuthUrl() string

GetAuthUrl retrieves the OAuth2 authorization service URL associated with the provider. It implements the GetAuthUrl() method of the Provider interface. The authorization service URL is where the user grants permission for the OAuth2 flow.

func (*OAuth2Config) GetClientId

func (oc *OAuth2Config) GetClientId() string

GetClientId retrieves the client ID associated with the OAuth2 provider. It implements the GetClientId() method of the Provider interface. The client ID is used to uniquely identify the application associated with the provider.

func (*OAuth2Config) GetClientSecret

func (oc *OAuth2Config) GetClientSecret() string

GetClientSecret retrieves the client secret associated with the OAuth2 provider. It implements the GetClientSecret() method of the Provider interface. The client secret is used for secure communication between the application and the provider.

func (*OAuth2Config) GetContext

func (oc *OAuth2Config) GetContext() context.Context

GetContext retrieves the context associated with the OAuth2 provider. It implements the GetContext() method of the Provider interface. The context is used to perform operations within the scope of the provider.

func (*OAuth2Config) GetDisplayName

func (oc *OAuth2Config) GetDisplayName() string

GetDisplayName retrieves the human-readable name of the OAuth2 provider. It implements the GetDisplayName() method of the Provider interface. The display name is typically used for UI or identification purposes.

func (*OAuth2Config) GetPKCE

func (oc *OAuth2Config) GetPKCE() bool

GetPKCE retrieves whether the OAuth2 provider can use the PKCE (Proof Key for Code Exchange) flow. It implements the GetPKCE() method of the Provider interface. PKCE enhances the security of OAuth2 authorization code grants.

func (*OAuth2Config) GetRedirectUrl

func (oc *OAuth2Config) GetRedirectUrl() string

GetRedirectUrl retrieves the redirect URL associated with the OAuth2 provider. It implements the GetRedirectUrl() method of the Provider interface. The redirect URL is where the user is redirected after completing the OAuth2 flow.

func (*OAuth2Config) GetScopes

func (oc *OAuth2Config) GetScopes() []string

GetScopes retrieves the access permissions that will be requested from the OAuth2 provider. It implements the GetScopes() method of the Provider interface. Scopes define the level of access the application is requesting from the user.

func (*OAuth2Config) GetTeamID

func (oc *OAuth2Config) GetTeamID() string

GetTeamID retrieves the Team ID associated with the OAuth2 provider. This is specifically used for Apple Sign In.

func (*OAuth2Config) GetTokenUrl

func (oc *OAuth2Config) GetTokenUrl() string

GetTokenUrl retrieves the OAuth2 token exchange service URL associated with the provider. It implements the GetTokenUrl() method of the Provider interface. The token exchange service URL is where the OAuth2 authorization code is exchanged for an access token.

func (*OAuth2Config) GetUserApiUrl

func (oc *OAuth2Config) GetUserApiUrl() string

GetUserApiUrl retrieves the user information API URL associated with the OAuth2 provider. It implements the GetUserApiUrl() method of the Provider interface. The user information API URL is used to fetch details about the authenticated user.

func (*OAuth2Config) SendRawUserDataRequest

func (oc *OAuth2Config) SendRawUserDataRequest(req *http.Request, token *oauth2.Token) ([]byte, error)

SendRawUserDataRequest sends the specified user data request and returns its raw response body. It is a helper method used internally to fetch user data.

func (*OAuth2Config) SetAuthUrl

func (oc *OAuth2Config) SetAuthUrl(url string)

SetAuthUrl assigns the specified OAuth2 authorization service URL to the OAuth2 provider. It implements the SetAuthUrl() method of the Provider interface. The authorization service URL is where the user grants permission for the OAuth2 flow.

func (*OAuth2Config) SetClientId

func (oc *OAuth2Config) SetClientId(clientId string)

SetClientId assigns the specified client ID to the OAuth2 provider. It implements the SetClientId() method of the Provider interface. The client ID is used to uniquely identify the application associated with the provider.

func (*OAuth2Config) SetClientSecret

func (oc *OAuth2Config) SetClientSecret(secret string)

SetClientSecret assigns the specified client secret to the OAuth2 provider. It implements the SetClientSecret() method of the Provider interface. The client secret is used for secure communication between the application and the provider.

func (*OAuth2Config) SetContext

func (oc *OAuth2Config) SetContext(ctx context.Context)

SetContext assigns the specified context to the OAuth2 provider. It implements the SetContext() method of the Provider interface. The context is crucial for performing operations within the scope of the provider.

func (*OAuth2Config) SetDisplayName

func (oc *OAuth2Config) SetDisplayName(displayName string)

SetDisplayName sets the human-readable name of the OAuth2 provider. It implements the SetDisplayName() method of the Provider interface. The display name is typically used for UI or identification purposes.

func (*OAuth2Config) SetPKCE

func (oc *OAuth2Config) SetPKCE(enable bool)

SetPKCE toggles the state whether the OAuth2 provider can use the PKCE flow or not. It implements the SetPKCE() method of the Provider interface. PKCE enhances the security of OAuth2 authorization code grants.

func (*OAuth2Config) SetRedirectUrl

func (oc *OAuth2Config) SetRedirectUrl(url string)

SetRedirectUrl assigns the specified redirect URL to the OAuth2 provider. It implements the SetRedirectUrl() method of the Provider interface. The redirect URL is where the user is redirected after completing the OAuth2 flow.

func (*OAuth2Config) SetScopes

func (oc *OAuth2Config) SetScopes(scopes []string)

SetScopes sets the access permissions that will be requested later during the OAuth2 flow. It implements the SetScopes() method of the Provider interface. Scopes define the level of access the application is requesting from the user.

func (*OAuth2Config) SetTeamID

func (oc *OAuth2Config) SetTeamID(teamID string)

SetTeamID assigns the specified Team ID to the OAuth2 provider. This is specifically used for Apple Sign In.

func (*OAuth2Config) SetTokenUrl

func (oc *OAuth2Config) SetTokenUrl(url string)

SetTokenUrl assigns the specified OAuth2 token exchange service URL to the OAuth2 provider. It implements the SetTokenUrl() method of the Provider interface. The token exchange service URL is where the OAuth2 authorization code is exchanged for an access token.

func (*OAuth2Config) SetUserApiUrl

func (oc *OAuth2Config) SetUserApiUrl(url string)

SetUserApiUrl assigns the specified user information API URL to the OAuth2 provider. It implements the SetUserApiUrl() method of the Provider interface. The user information API URL is used to fetch details about the authenticated user.

type Provider

type Provider interface {
	// GetContext retrieves the context associated with the provider (if any).
	GetContext() context.Context

	// SetContext assigns the specified context to the current provider.
	SetContext(ctx context.Context)

	// GetDisplayName usually returns the official name of the provider as written by the service.
	// It can be used directly in user interfaces.
	GetDisplayName() string

	// SetDisplayName sets the display name of the OAuth2 provider.
	SetDisplayName(displayName string)

	// GetClientId retrieves the client ID associated with the provider.
	GetClientId() string

	// SetClientId sets the client ID of the OAuth2 provider.
	SetClientId(clientId string)

	// GetClientSecret retrieves the client secret associated with the provider.
	GetClientSecret() string

	// SetClientSecret sets the client secret of the OAuth2 provider.
	SetClientSecret(secret string)

	// GetRedirectUrl retrieves the URL where the user is redirected after OAuth2 authentication.
	GetRedirectUrl() string

	// SetRedirectUrl sets the redirect URL of the OAuth2 provider.
	SetRedirectUrl(url string)

	// GetAuthUrl retrieves the authorization service URL of the OAuth2 provider.
	GetAuthUrl() string

	// SetAuthUrl sets the authorization service URL of the OAuth2 provider.
	SetAuthUrl(url string)

	// GetTokenUrl retrieves the token exchange service URL of the OAuth2 provider.
	GetTokenUrl() string

	// SetTokenUrl sets the token exchange service URL of the OAuth2 provider.
	SetTokenUrl(url string)

	// GetUserApiUrl retrieves the user information API URL of the OAuth2 provider.
	GetUserApiUrl() string

	// SetUserApiUrl sets the user information API URL of the OAuth2 provider.
	SetUserApiUrl(url string)

	// GetScopes retrieves the access permissions that will be requested during the OAuth2 flow.
	GetScopes() []string

	// SetScopes sets the access permissions that will be requested during the OAuth2 flow.
	SetScopes(scopes []string)

	// GetPKCE retrieves whether the provider can use the PKCE (Proof Key for Code Exchange) flow.
	GetPKCE() bool

	// SetPKCE toggles the state of PKCE flow for the OAuth2 provider.
	SetPKCE(enable bool)

	// Client returns an HTTP client configured with the provided OAuth2 token.
	Client(token *oauth2.Token) *http.Client

	// BuildAuthUrl returns the URL to the OAuth2 provider's consent page, asking for explicit permissions.
	BuildAuthUrl(state string, opts ...oauth2.AuthCodeOption) string

	// FetchToken converts an authorization code to an OAuth2 token.
	FetchToken(code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)

	// FetchRawData requests and marshals the raw OAuth user API response.
	FetchRawData(token *oauth2.Token) ([]byte, error)

	// FetchUser is similar to FetchRawData but normalizes and marshals the user API response into a standardized Credential struct.
	FetchUser(token *oauth2.Token) (user *Credential, err error)

	// ValidateConfig validates the provider configuration.
	ValidateConfig() error

	// RefreshToken refreshes the OAuth2 token using the refresh token.
	RefreshToken(token *oauth2.Token) (*oauth2.Token, error)
}

Provider defines a common interface for OAuth2 client implementations. It abstracts the necessary methods and properties required for OAuth2 authentication.

Jump to

Keyboard shortcuts

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