Golang OpenID Connect Client

Overview

adhocore/goic

Latest Version Software License Go Report Donate 15 Donate 25 Donate 50 Tweet

GOIC, Go Open ID Connect, is OpenID connect client library for Golang. It supports the Authorization Code Flow of OpenID Connect specification. It doesn't yet support refresh_token grant type and that will be added later.

It is a weekend hack project and is work in progress and not production ready yet.

Installation

go get github.com/adhocore/goic

Usage

Decide an endpoint (aka URI) in your server where you would like goic to intercept and add OpenID Connect flow. Let's say /auth/o8. Then the provider name follows it. All the OpenID providers that your server should support will need a unique name and each of the providers get a URI like so /auth/o8/<name>. Example:

Provider Name OpenID URI
Google google /auth/o8/google
Microsoft microsoft /auth/o8/microsoft

All the providers must provide .well-known configurations for OpenID auto discovery.

Get ready with OpenID provider credentials (client id and secret). For Google, check this. To use the example below you need to export GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET env vars.

You also need to configure application domain and redirect URI in the Provider console/dashboard. (redirect URI is same as OpenID URI in above table).

Below is an example code but instead of copy/pasting it entirely you can use it for reference.

package main

import (
	"log"
	"net/http"
	"os"

	"github.com/adhocore/goic"
)

func main() {
	// Init GOIC with a root uri and verbose mode (=true)
	g := goic.New("/auth/o8", true)

	// Register Google provider with name google and its auth URI
	// It will preemptively load well-known config and jwks keys
	p := g.NewProvider("google", "https://accounts.google.com")

	// Configure credentials for Google provider
	p.WithCredential(os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_CLIENT_SECRET"))

	// Configure scope
	p.WithScope("openid email profile")

	// Define a callback that will receive token and user info on successful verification
	g.UserCallback(func(t *goic.Token, u *goic.User, w http.ResponseWriter, r *http.Request) {
		// Persist token and user info as you wish! Be sure to check for error in `u.Error` first
		// Use the available `w` and `r` params to show some nice page with message to your user
		// OR redirect them to homepage/dashboard etc

		// However, for the example, here I just dump it in backend console
		log.Println("token: ", t)
		log.Println("user: ", u)

		// and tell the user it is all good:
		_, _ = w.Write([]byte("All good, check backend console"))
	})

	// Listen address for server, 443 for https as OpenID connect mandates it!
	addr := "localhost:443"
	// You need to find a way to run your localhost in HTTPS as well.
	// You may also alias it something like `goic.lvh.me` (lvh is local virtual host)
	// *.lvh.me is automatically mapped to 127.0.0.1 in unix systems.

	// A catch-all dummy handler
	handler := func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(r.Method + " " + r.URL.Path))
	}

	log.Println("Server running on https://localhost")
	log.Println("            Visit https://localhost/auth/o8/google")

	// This is just example (don't copy it)
	useMux := os.Getenv("GOIC_HTTP_MUX") == "1"
	if useMux {
		mux := http.NewServeMux()
		// If you use http mux, wrap your handler with g.MiddlewareHandler
		mux.Handle("/", g.MiddlewareHandler(http.HandlerFunc(handler)))
		server := &http.Server{Addr: addr, Handler: mux}
		log.Fatal(server.ListenAndServeTLS("server.crt", "server.key"))
	} else {
		// If you just use plain simple handler func,
		// wrap your handler with g.MiddlewareFunc
		http.HandleFunc("/", g.MiddlewareFunc(handler))
		log.Fatal(http.ListenAndServeTLS(addr, "server.crt", "server.key", nil))
	}
}
// OR, you can use shorthand syntax to register providers:

g := goic.New("/auth/o8", false)
g.AddProvider(goic.Google.WithCredential(os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_CLIENT_SECRET")))
g.AddProvider(goic.Microsoft.WithCredential(os.Getenv("MICROSOFT_CLIENT_ID"), os.Getenv("MICROSOFT_CLIENT_SECRET")))

// ...

After having code like that, build the binary (go build) and run server program (./<binary>).

You need to point Sign in with <provider> button to https://localhost/auth/o8/<provider> for your end user. For example:

<a href="https://localhost/auth/o8/google">Sign in with Google</a>
<a href="https://localhost/auth/o8/microsoft">Sign in with Microsoft</a>

The complete flow is managed and handled by GOIC for you and on successful verification, You will be able to receive user and token info in your callback via g.UserCallback! That is where you persist the user data, set some cookie etc.

Check examples directory later for more, as it will be updated when GOIC has new features.

The example and discussion here assume localhost domain so adjust that accordingly for your domains.

Demo

GOIC has been implemented in opensource project adhocore/urlsh:

Provider Name Demo URL
Google google urlssh.xyz/auth/o8/google
Microsoft microsoft urlssh.xyz/auth/o8/microsoft

On successful verification your information is echoed back to you as JSON but not saved in server (pinky promise).


TODO

  • Support refresh token grant_type
  • Tests and more tests
  • Release stable version
  • Support OpenID Implicit Flow Check #3

License

© MIT | 2021-2099, Jitendra Adhikari

Credits

Release managed by please.


Other projects

My other golang projects you might find interesting and useful:

  • gronx - Lightweight, fast and dependency-free Cron expression parser (due checker), task scheduler and/or daemon for Golang (tested on v1.13 and above) and standalone usage.
  • urlsh - URL shortener and bookmarker service with UI, API, Cache, Hits Counter and forwarder using postgres and redis in backend, bulma in frontend; has web and cli client
  • fast - Check your internet speed with ease and comfort right from the terminal
Issues
Releases(v0.0.12)
  • v0.0.12(Oct 16, 2021)

    Features

    • Add RevokeToken (Jitendra Adhikari) b8f3678
    • Add helper funcs to check abilities and create auth header (Jitendra Adhikari) 545c012

    Bug Fixes

    • Token is not mandatory for signout (Jitendra Adhikari) da50d61
    • Some provider like yahoo uses key token_revocation_endpoint (Jitendra Adhikari) c78812c

    Miscellaneous

    • Add revoke token example (Jitendra Adhikari) b7c04c5

    Documentations

    • Ability support matrix (Jitendra) 070f1d3
    • Func doc (Jitendra Adhikari) 6b9e0b0
    • Code clarity (Jitendra Adhikari) 066e7c2
    • Add revocation section and code snippet (Jitendra Adhikari) 9cf00c0
    • Cleanup misinfo (Jitendra) 1fc483b
    Source code(tar.gz)
    Source code(zip)
  • v0.0.11(Oct 15, 2021)

  • v0.0.10(Oct 14, 2021)

    Features

    • Support refresh_token grant (Jitendra Adhikari) 27b2267

    Internal Refactors

    • Rename func arg, fix auth code grant (Jitendra Adhikari) a8ed467
    • Make RequestAuth able to be used standalone from outside (Jitendra Adhikari) cfec49a

    Miscellaneous

    • Use printf (Jitendra Adhikari) 0cb25d8
    • Update docs, cleanup unused (Jitendra Adhikari) 1bdb0cd

    Documentations

    • Add detailed API docs for standalone/manual usage (Jitendra Adhikari) 26ac14e
    • Add yahoo docs (Jitendra Adhikari) af8126f
    Source code(tar.gz)
    Source code(zip)
  • v0.0.9(Oct 14, 2021)

    Features

    • Add Yahoo provider (Jitendra Adhikari) d9d12af
    • Support ecdsa key/algo (Jitendra Adhikari) 68866a1
    • Support ecdsa key/algo (Jitendra Adhikari) 1079448

    Bug Fixes

    • Key check order/clause for rsa and ec (Jitendra Adhikari) 9f29c79

    Internal Refactors

    • Delete state immediately, fix error HTML (Jitendra Adhikari) 3db1dff

    Miscellaneous

    • Update yahoo example (Jitendra Adhikari) f223c06

    Documentations

    • Add yahoo demo (Jitendra Adhikari) 803e8e4
    Source code(tar.gz)
    Source code(zip)
  • v0.0.8(Oct 13, 2021)

    Internal Refactors

    • Add/use errorHTML() helper, validate provider, show retry url (Jitendra Adhikari) 0c5431e
    • Extract user and token struct and func (Jitendra Adhikari) 931cb6e
    • Extract user struct, unset state, log if verbose (Jitendra Adhikari) 1192822

    Documentations

    Source code(tar.gz)
    Source code(zip)
  • v0.0.7(Oct 12, 2021)

  • v0.0.6(Oct 12, 2021)

    Features

    • Add ready instances of providers for google and microsoft (Jitendra Adhikari) 55c2ba4
    • Add addProvider() (Jitendra Adhikari) a6b1524

    Bug Fixes

    • Switch to form-url-encoded from json (Jitendra Adhikari) 1a4bc17

    Internal Refactors

    • Google example (Jitendra Adhikari) cc94831
    • AQAB is frequently used and is is 65537 (Jitendra Adhikari) 0ff7b85
    • Update json meta, error msg fmt, cleanup imports (Jitendra Adhikari) c8e4b92

    Miscellaneous

    • Add example with all providers (Jitendra Adhikari) ee4e86b
    • Add microsoft example (Jitendra Adhikari) 255794a

    Documentations

    • Update example, login anchor and demo section (Jitendra Adhikari) ab52e67
    Source code(tar.gz)
    Source code(zip)
  • v0.0.5(Oct 11, 2021)

    Features

    • Add base64 url decoder and use from parseModulo(), parseExponent() (Jitendra Adhikari) fdfd3af

    Internal Refactors

    • Use shorthand func param types, update verbose msg format (Jitendra Adhikari) 19a1bca
    • Extract verifyClaims() from verifyToken() (Jitendra Adhikari) 8672ae9

    Documentations

    • Update demo section (Jitendra) 2095357
    • Add demo URL (Jitendra) f0afa31
    • Minor updates (Jitendra) 8dfb403
    Source code(tar.gz)
    Source code(zip)
  • v0.0.4(Oct 11, 2021)

  • v0.0.3(Oct 11, 2021)

  • v0.0.2(Oct 11, 2021)

  • v0.0.1(Oct 11, 2021)

    Features

    • Add google example (Jitendra Adhikari) 49c2518
    • Add goic, the main program (Jitendra Adhikari) 90839b1
    • Define provider struct, add related functionality (Jitendra Adhikari) 21fe302
    • Add util for common tasks (Jitendra Adhikari) 5896ea2

    Miscellaneous

    • Add go mod stuffs (Jitendra Adhikari) 3bdcd00
    • Add license (Jitendra Adhikari) 2963a4b
    • Add dotfiles (Jitendra Adhikari) 8f76c5c

    Documentations

    • Add README (Jitendra Adhikari) 252eae9
    Source code(tar.gz)
    Source code(zip)
Owner
Jitendra
ISTJ. Thinker. Solver. Creator.
Jitendra
ZITADEL - Identity Experience Platform

What Is ZITADEL ZITADEL is a "Cloud Native Identity and Access Management" solution built for the cloud era. ZITADEL uses a modern software stack cons

CAOS 226 Oct 22, 2021
Go library providing in-memory implementation of an OAuth2 Authorization Server / OpenID Provider

dispans Go library providing in-memory implementation of an OAuth2 Authorization Server / OpenID Provider. The name comes from the Swedish word dispen

Xenit AB 3 Oct 7, 2021
manipulate WireGuard with OpenID Connect Client Initiated Backchannel Authentication(CIBA) Flow

oidc-wireguard-vpn manipulate WireGuard with OpenID Connect Client Initiated Backchannel Authentication(CIBA) Flow Requirements Linux WireGuard nftabl

Kurochan 20 Oct 2, 2021
an SSO and OAuth / OIDC login solution for Nginx using the auth_request module

Vouch Proxy An SSO solution for Nginx using the auth_request module. Vouch Proxy can protect all of your websites at once. Vouch Proxy supports many O

Vouch 1.6k Oct 20, 2021
⛩️ Go library for protecting HTTP handlers with authorization bearer token.

G8, pronounced Gate, is a simple Go library for protecting HTTP handlers with tokens. Tired of constantly re-implementing a security layer for each

Chris C. 31 Oct 11, 2021
an stateless OpenID Connect authorization server that mints ID Tokens from Webauthn challenges

Webauthn-oidc Webauthn-oidc is a very minimal OIDC authorization server that only supports webauthn for authentication. This can be used to bootstrap

Arian van Putten 4 Oct 20, 2021
Certificate authority and access plane for SSH, Kubernetes, web applications, and databases

Teleport is an identity-aware, multi-protocol access proxy which understands SSH, HTTPS, Kubernetes API, MySQL and PostgreSQL wire protocols.

Teleport 10.2k Oct 17, 2021
The Single Sign-On Multi-Factor portal for web apps

Authelia is an open-source authentication and authorization server providing two-factor authentication and single sign-on (SSO) for your applications

Authelia 10.6k Oct 22, 2021
Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applications.

Goth: Multi-Provider Authentication for Go Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applic

Mark Bates 3.4k Oct 24, 2021
A fast and simple JWT implementation for Go

JWT Fast and simple JWT implementation written in Go. This package was designed with security, performance and simplicity in mind, it protects your to

Gerasimos (Makis) Maropoulos 113 Oct 21, 2021
An authentication proxy for Google Cloud managed databases

db-auth-gateway An authentication proxy for Google Cloud managed databases. Based on the ideas of cloudsql-proxy but intended to be run as a standalon

null 21 Oct 9, 2021
a Framework for creating mesh networks using technologies and design patterns of Erlang/OTP in Golang

Ergo Framework Implementation of Erlang/OTP in Golang. Up to x5 times faster than original Erlang/OTP. The easiest drop-in replacement for your hot no

Taras Halturin 1.1k Oct 17, 2021
A library for performing OAuth Device flow and Web application flow in Go client apps.

oauth A library for Go client applications that need to perform OAuth authorization against a server, typically GitHub.com. Traditionally,

GitHub CLI 288 Oct 18, 2021
Golang OAuth2 server library

OSIN Golang OAuth2 server library OSIN is an OAuth2 server library for the Go language, as specified at http://tools.ietf.org/html/rfc6749 and http://

OpenShift 1.7k Oct 21, 2021
simple-jwt-provider - Simple and lightweight provider which exhibits JWTs, supports login, password-reset (via mail) and user management.

Simple and lightweight JWT-Provider written in go (golang). It exhibits JWT for the in postgres persisted user, which can be managed via api. Also, a password-reset flow via mail verification is available. User specific custom-claims also available for jwt-generation and mail rendering.

Max 20 Oct 6, 2021
JWT login microservice with plugable backends such as OAuth2, Google, Github, htpasswd, osiam, ..

loginsrv loginsrv is a standalone minimalistic login server providing a JWT login for multiple login backends. ** Attention: Update to v1.3.0 for Goog

tarent 1.8k Oct 16, 2021
auth0 jwt validator with jwks caching

JWT Validator for Auth0 (https://auth0.com/) that caches public JWKS (since there is a limit on calls to public JWKS URL) Example securing a GraphQL s

null 0 Oct 20, 2021
Fast, secure and efficient secure cookie encoder/decoder

Encode and Decode secure cookies This package provides functions to encode and decode secure cookie values. A secure cookie has its value ciphered and

Christophe Meessen 54 Oct 8, 2021
OAuth 2.0 middleware service for chi (ported from gin by community member)

oauth middleware OAuth 2.0 Authorization Server & Authorization Middleware for go-chi This library was ported to go-chi from https://github.com/maxzer

go-chi 9 Oct 9, 2021