Golang OpenID Connect Client

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
Owner
Similar Resources

A library for Go client applications that need to perform OAuth authorization against a server

A library for Go client applications that need to perform OAuth authorization against a server

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

Oct 13, 2021

Go client library for the Auth0 platform.

Auth0 Go SDK Go client library for the Auth0 platform. Note: This SDK was previously maintained under go-auth0/auth0. Table of Contents Installation D

Dec 30, 2022

Golang Skeleton With Fully Managed Versions For Kick Start GoLang Project Development

Golang Skeleton With Fully Managed Versions For Kick Start GoLang Project Development

Golang Skeleton With Fully Managed Versions For Kick Start GoLang Project Development There is no doubt that Golang’s good documentation and intellige

Dec 31, 2022

Oauth2-golang - Oauth2 Golang Mysql

Oauth2-golang - Oauth2 Golang Mysql

Sep 16, 2022

An authorization library that supports access control models like ACL, RBAC, ABAC in Golang

An authorization library that supports access control models like ACL, RBAC, ABAC in Golang

Casbin News: still worry about how to write the correct Casbin policy? Casbin online editor is coming to help! Try it at: https://casbin.org/editor/ C

Jan 2, 2023

Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.

❗ Cache package has been moved to libcache repository Go-Guardian Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to

Dec 23, 2022

A standalone, specification-compliant, OAuth2 server written in Golang.

A standalone, specification-compliant,  OAuth2 server written in Golang.

Go OAuth2 Server This service implements OAuth 2.0 specification. Excerpts from the specification are included in this README file to describe differe

Dec 28, 2022

goRBAC provides a lightweight role-based access control (RBAC) implementation in Golang.

goRBAC goRBAC provides a lightweight role-based access control implementation in Golang. For the purposes of this package: * an identity has one or mo

Dec 29, 2022

This is an implementation of JWT in golang!

jwt This is a minimal implementation of JWT designed with simplicity in mind. What is JWT? Jwt is a signed JSON object used for claims based authentic

Oct 25, 2022
An OpenID Connect reference implementation in Golang

oidc-go-client An OpenID Connect reference implementation in Golang Getting started First clone the repository: git clone https://github.com/yufuid/oi

Dec 3, 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

Nov 6, 2022
An implementation for an OpenID Connect Provider in Go.

oidc-go This is an implementation of an OpenID Connect Provider (OP) as defined by OpenID that is meant to be a full, production ready OP. Features: E

Oct 7, 2022
A cli to asist developers in development and testing locally against OpenId Connect.

oidc-cli oidc-cli assists developers in automating authorization flow for local development and testing purpose. Installation Download the program fro

Feb 7, 2022
Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication
Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication

Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication

Jan 8, 2023
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

Dec 22, 2021
Demonstration of sharing secret data between an OAuth/OIDC client and an Identity Providers web client.

OAuth / OIDC Cubbyhole Share secret data between client applications. This is mostly a demonstration of some of the work I've been evaluating at Storj

Mar 21, 2022
A library for performing OAuth Device flow and Web application flow in Go client apps.
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,

Dec 30, 2022
Go module that allows you to authenticate to Azure with a well known client ID using interactive logon and grab the token

azureimposter Go module that pretends to be any clientID and grabs an authentication token from Azure using interactive login (w/mfa if enabled) and r

Dec 14, 2022
This repository contains a set of tools to help you implement IndieAuth, both server and client, in Go.

This repository contains a set of tools to help you implement IndieAuth, both server and client, in Go.

Nov 26, 2022