Categorygithub.com/mstgnz/goauth
modulepackage
1.2.0
Repository: https://github.com/mstgnz/goauth.git
Documentation: pkg.go.dev

# README

goauth

Go Reference Go Report Card License: MIT

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:

ProviderDocumentation
AppleApple Developer
DiscordDiscord Developer
FacebookFacebook for Developers
GiteaGitea Developer
GiteeGitee Developer
GitHubGitHub Developer
GitLabGitLab Developer
GoogleGoogle Identity Platform
InstagramInstagram Graph API
KakaoKakao Developers
LiveChatLiveChat API
MailcowMailcow API
MicrosoftMicrosoft Identity Platform
OIDCOpenID Connect
PatreonPatreon API
SpotifySpotify for Developers
StravaStrava API
TwitchTwitch Developers
X (Twitter)X Developer
VKVK API
YandexYandex 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.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

provider.BaseProvider implements common functionality for all providers.
Credential defines a standardized OAuth2 user data structure.
OAuth2Config encapsulates common attributes and behaviors shared among OAuth2 providers.

# Interfaces

Provider defines a common interface for OAuth2 client implementations.