Thanks to visit codestin.com
Credit goes to github.com

Skip to content

A Go library for TUM (Technical University of Munich) OIDC authentication with PKCE support and HTTP handlers

Notifications You must be signed in to change notification settings

robertjndw/go-tum-login-oidc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-tum-login-oidc

A Go library for TUM-Login OIDC authentication with PKCE support and ready-to-use HTTP handlers.

Features

  • TUM-specific OIDC integration with default configuration for TUM's identity provider
  • PKCE (Proof Key for Code Exchange) support for enhanced security
  • Ready-to-use HTTP handlers for login, callback, and logout flows
  • Session management with secure state and nonce handling
  • Framework agnostic with examples for standard net/http and Gin
  • User information extraction with TUM-specific claims support

Installation

go get github.com/robertjndw/go-tum-login-oidc

Quick Start

Basic HTTP Server

package main

import (
    "context"
    "log"
    "net/http"
    "os"
    
    tumoidc "github.com/robertjndw/go-tum-login-oidc"
)

func main() {
    // Initialize OIDC client
    oidcClient, err := tumoidc.New(context.Background(),
        os.Getenv("TUM_CLIENT_ID"),
        tumoidc.WithRedirectURL("http://localhost:8080/callback"),
        tumoidc.WithScopes("profile", "email"),
    )
    if err != nil {
        log.Fatal("Failed to create OIDC client:", err)
    }

    // Create HTTP handler
    handler := tumoidc.NewHTTPHandler(oidcClient)
    
    http.Handle("/login", handler.Login())
    http.Handle("/callback", handler.HandleCallback(func(w http.ResponseWriter, r *http.Request, user *tumoidc.UserInfo) {
        log.Printf("User authenticated: %s (%s)", user.Name, user.UserName)
        http.Redirect(w, r, "/", http.StatusFound)
    }))
    http.Handle("/logout", handler.Logout())

    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

With Gin Framework

package main

import (
    "context"
    "log"
    "net/http"
    "os"
    
    "github.com/gin-gonic/gin"
    tumoidc "github.com/robertjndw/go-tum-login-oidc"
)

func main() {
    oidcClient, err := tumoidc.New(context.Background(),
        os.Getenv("TUM_CLIENT_ID"),
        tumoidc.WithRedirectURL("http://localhost:8080/callback"),
        tumoidc.WithScopes("profile", "email"),
    )
    if err != nil {
        log.Fatal("Failed to create OIDC client:", err)
    }

    handler := tumoidc.NewHTTPHandler(oidcClient)
    r := gin.Default()
    
    r.GET("/login", gin.WrapH(handler.Login()))
    r.GET("/callback", gin.WrapH(handler.HandleCallback(func(w http.ResponseWriter, r *http.Request, user *tumoidc.UserInfo) {
        // Process authenticated user
        log.Printf("User authenticated: %s", user.Name)
        http.Redirect(w, r, "/", http.StatusFound)
    })))
    r.GET("/logout", gin.WrapH(handler.Logout()))

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

Configuration

Options

The library uses functional options for configuration:

// Required: Create client with client ID
oidcClient, err := tumoidc.New(ctx, "your-client-id")

// With optional configuration
oidcClient, err := tumoidc.New(ctx, "your-client-id",
    tumoidc.WithClientSecret("your-secret"),    // Optional: For confidential clients
    tumoidc.WithRedirectURL("http://..."),       // Required: Callback URL
    tumoidc.WithScopes("profile", "email"),      // Optional: Additional scopes (openid is default)
    tumoidc.WithIssuer("https://..."),           // Optional: Custom issuer (defaults to TUM's issuer)
)

User Information

The library extracts user information into a structured format:

type UserInfo struct {
    Sub                  string   `json:"sub"`
    Name                 string   `json:"name"`
    GivenName            string   `json:"given_name"`
    FamilyName           string   `json:"family_name"`
    UserName             string   `json:"preferred_username"`
    EduPersonAffiliation []string `json:"eduPersonAffiliation,omitempty"`
}

Advanced Usage

Manual OIDC Flow

For more control over the authentication flow:

// Generate PKCE parameters
pkce, err := oidcClient.GeneratePKCE()
if err != nil {
    // handle error
}

// Generate auth URL
authURL := oidcClient.AuthCodeURL(pkce.State, pkce.CodeChallenge, nonce)

// Later, exchange code for token
token, err := oidcClient.ExchangeCode(ctx, code, pkce.CodeVerifier, nonce)
if err != nil {
    // handle error
}

// Get user info
userInfo, err := oidcClient.UserInfo(ctx, token)
if err != nil {
    // handle error
}

Security Features

  • PKCE Support: Implements Proof Key for Code Exchange for enhanced security
  • State Parameter: Prevents CSRF attacks during OAuth flow
  • Nonce Validation: Protects against token replay attacks
  • Secure Sessions: Uses cryptographically secure random generators
  • Token Verification: Validates ID tokens and signatures

Examples

See the examples/ directory for complete working examples:

Set environment variables for client ID and secret:

export TUM_CLIENT_ID="your-client-id"
export TUM_CLIENT_SECRET="your-client-secret"  # If using confidential client

Run the examples:

go run examples/http/main.go
# or
go run examples/gin/main.go

Testing

Run the test suite:

go test ./...

Requirements

License

This project is licensed under the MIT License.

About

A Go library for TUM (Technical University of Munich) OIDC authentication with PKCE support and HTTP handlers

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages