• Stars
    star
    579
  • Rank 77,126 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created about 9 years ago
  • Updated 21 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Middleware for Gin Framework users who also want to use OAuth2

Gin-OAuth2

Go Report Card Build Status GoDoc

Gin-OAuth2 is specially made for Gin Framework users who also want to use OAuth2. It was created by Go developers who needed Gin middleware for working with OAuth2 and couldn't find any.

Project Context and Features

When it comes to choosing a Go framework, there's a lot of confusion about what to use. The scene is very fragmented, and detailed comparisons of different frameworks are still somewhat rare. Meantime, how to handle dependencies and structure projects are big topics in the Go community. We've liked using Gin for its speed, accessibility, and usefulness in developing microservice architectures. In creating Gin-OAuth2, we wanted to take fuller advantage of Gin's capabilities and help other devs do likewise.

Gin-OAuth2 is expressive, flexible, and very easy to use. It allows you to:

  • do OAuth2 authorization based on HTTP routing
  • create router groups to place OAuth2 authorization on top, using HTTP verbs and passing them
  • more easily decouple services by promoting a "say what to do, not how to do it" approach
  • configure your REST API directly in the code (see the "Usage" example below)
  • write your own authorization functions

How OAuth 2 Works

If you're just starting out with OAuth2, you might find these resources useful:

Requirements

  • Gin
  • An OAuth2 Token provider (we recommend that you use your own, p.e. use dex)
  • a Tokeninfo service (p.e. use dex)

Gin-OAuth2 uses the following Go packages as dependencies:

Installation

Assuming you've installed Go and Gin, run this:

go get github.com/zalando/gin-oauth2

Usage

This example shows you how to use Gin-OAuth2.

Uid-Based Access

First, define your access triples to identify who has access to a given resource. This snippet shows how to grant resource access to two hypothetical employees:

    // from zalando package
    // type AccessTuple struct {
    //      Realm string // p.e. "employees", "services"
    //      Uid   string // UnixName
    //      Cn    string // RealName
    // }
    var USERS []zalando.AccessTuple = []zalando.AccessTuple{
    {"/employees", "sszuecs", "Sandor SzΓΌcs"},
        {"/employees", "njuettner", "Nick JΓΌttner"},
    }

Next, define which Gin middlewares you use. The third line in this snippet is a basic audit log:

router := gin.New()
router.Use(ginglog.Logger(3 * time.Second))
router.Use(ginoauth2.RequestLogger([]string{"uid"}, "data"))
router.Use(gin.Recovery())

Finally, define which type of access you grant to the defined users. We'll use a router group, so that we can add a bunch of router paths and HTTP verbs:

privateUser := router.Group("/api/privateUser")
privateUser.Use(ginoauth2.Auth(zalando.UidCheck(USERS), zalando.OAuth2Endpoint))
privateUser.GET("/", func(c *gin.Context) {
	if v, ok := c.Get("cn"); ok {
		c.JSON(200, gin.H{"message": fmt.Sprintf("Hello from private for users to %s", v)})
	} else {
		c.JSON(200, gin.H{"message": "Hello from private for users without cn"})
	}
})

Testing

To test, you can use curl:

    curl -H "Authorization: Bearer $TOKEN" http://localhost:8081/api/privateUser/
    {"message":"Hello from private for users to Sandor SzΓΌcs"}

Team-Based Access

As with Uid-based access, define your access triples to identify who has access to a given resource. With this snippet, you can grant resource access to an entire team instead of individuals:

    var TEAMS []zalando.AccessTuple = []zalando.AccessTuple{
    {"teams", "opensourceguild", "OpenSource Guild"},
    {"teams", "tm", "Platform / System"},
    {"teams", "teapot", "Platform / Cloud API"},
    }

Now define which Gin middlewares you use:

router := gin.New()
router.Use(ginglog.Logger(3 * time.Second))
router.Use(ginoauth2.RequestLogger([]string{"uid"}, "data"))
router.Use(gin.Recovery())

Lastly, define which type of access you grant to the defined team. We'll use a router group again:

privateGroup := router.Group("/api/privateGroup")
privateGroup.Use(ginoauth2.Auth(zalando.GroupCheck(TEAMS), zalando.OAuth2Endpoint))
privateGroup.GET("/", func(c *gin.Context) {
	uid, okUid := c.Get("uid")
	if team, ok := c.Get("team"); ok && okUid {
		c.JSON(200, gin.H{"message": fmt.Sprintf("Hello from private to %s member of %s", uid, team)})
	} else {
		c.JSON(200, gin.H{"message": "Hello from private for groups without uid and team"})
	}
})

Once again, you can use curl to test:

    curl -H "Authorization: Bearer $TOKEN" http://localhost:8081/api/privateGroup/
    {"message":"Hello from private to sszuecs member of teapot"}

Run Example Service

Run example service:

% go run example/zalando/main.go -v=2 -logtostderr
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env:   export GIN_MODE=release
- using code:  gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET   /api/                     --> main.funcΒ·001 (4 handlers)
I1028 10:12:44.908274   22325 ginoauth2.go:238] Register allowed users: [{Realm:employees Uid:sszuecs Cn:Sandor SzΓΌcs} {Realm:employees Uid:njuettner Cn:Nick JΓΌttner}]
[GIN-debug] GET   /api/private/             --> main.funcΒ·002 (5 handlers)
I1028 10:12:44.908342   22325 main.go:41] bootstrapped application
[GIN-debug] Listening and serving HTTP on :8081
I1028 10:12:46.794502   22325 ginoauth2.go:213] Grant access to sszuecs
I1028 10:12:46.794571   22325 ginglog.go:93] [GIN] | 200 | 194.162911ms | [::1]:58629 |   GET     /api/private/

Get an access token from your token provider (oauth2.Endpoint.AuthURL):

% TOKEN=$(curl https://$USER:[email protected]/access_token)

Request:

% curl -H "Authorization: Bearer $TOKEN" http://localhost:8081/api/privateGroup/
{"message":"Hello from private to sszuecs member of teapot"}

Google-Based Access

As shown in this great article about Gin and Google signin, you have to create credentials for an "OAuth client ID." In your Google Cloud Console, you will find "Credentials" in the "API Manager":

Picture of Google Cloud Console showing API Manager

You have to specify a path to your clientid credential file and a slice of scopes that you request for authorization. You have also to specify the URL to get redirected to upon completion of the Google OAuth2. Lastly, you have to choose a secret for the CookieStore and a session. This OAuth2 flow is also known as Authorization Code Flow.

    redirectURL := "http://127.0.0.1:8081/auth/"
    credFile := "./example/google/test-clientid.google.json" // you have to build your own
    scopes := []string{
           "https://www.googleapis.com/auth/userinfo.email",
           // You have to select your own scope from here -> https://developers.google.com/identity/protocols/googlescopes#google_sign-in
}
secret := []byte("secret") //
sessionName := "goquestsession"

router := gin.Default()
// init settings for google auth
google.Setup(redirectURL, credFile, scopes, secret)
router.Use(google.Session(sessionName))

After the base setup, register a login handler. You might want to implement it yourself (pull requests are welcome):

router.GET("/login", google.LoginHandler)

With a publicly accessible login resource in place, we can protect a private router group accessibly only with a Google authorized session. Auth will save your user information in the Gin context bucket "user."

// protected url group
private := router.Group("/auth")
private.Use(google.Auth())
private.GET("/", UserInfoHandler)
private.GET("/api", func(ctx *gin.Context) {
	ctx.JSON(200, gin.H{"message": "Hello from private for groups"})
})

router.Run("127.0.0.1:8081")

A handler will fetch user information from the gin.Context that's stored in google.Auth.

    func UserInfoHandler(ctx *gin.Context) {
        ctx.JSON(http.StatusOK, gin.H{"Hello": "from private", "user": ctx.MustGet("user").(google.User)})
    }

Testing Google Auth

  • Created your Google clientid stored in clientid.google.json similar to and grant redirect to example/google/test-clientid.google.json as described in the article mentioned before.
  • run the server: % go run example/google/google.go -cred-file clientid.google.json
  • open http://127.0.0.1:8081/login in your browser
  • In your browser, follow the login, and choose your identity to login with
  • You'll be redirected to the http://127.0.0.1:8081/auth endpoint, which should show your identity data

GitHub-Based Access

As shown in this blog post about Go and GitHub signin, you have to register your application with GitHub to get an "OAuth client ID." In your developer applications, you will find your "Credentials":

From this article the flow of OAuth2 is:

  • the user is on your website and clicks β€œlogin with GitHub” link
  • you redirect the user to GitHub’s authorization page. In that url you specify desired access level and a random secret the user authorizes your app by clicking on a link
  • GitHub redirects to a callback url on your website (which you provided when registering the app with GitHub)
  • in the url handler, extract β€œsecret” and β€œcode” args
  • you have to check that the secret is the same as the one you sent to GitHub (security measure that prevents forgery)
  • you call another GitHub url to exchange code for access token

You have to specify a path to your clientid credential file and a slice of scopes that you request for authorization. You have also to specify the URL to get redirected to upon completion of the GitHub OAuth2. Lastly, you have to choose a secret for the CookieStore and a session. This OAuth2 flow is also known as Authorization Code Flow.

    redirectURL := "http://127.0.0.1:8081/auth/"
    credFile := "./example/github/test-clientid.github.json" // you have to build your own
    scopes := []string{
           "repo",
           // You have to select your own scope from here -> https://developer.github.com/v3/oauth/#scopes
}
secret := []byte("secret") //
sessionName := "goquestsession"

router := gin.Default()
// init settings for github auth
github.Setup(redirectURL, credFile, scopes, secret)
router.Use(github.Session(sessionName))

After the base setup, register a login handler. You might want to implement it yourself (pull requests are welcome):

router.GET("/login", github.LoginHandler)

With a publicly accessible login resource in place, we can protect a private router group accessibly only with a GitHub authorized session. Auth will save your user information in the Gin context bucket "user."

// protected url group
private := router.Group("/auth")
private.Use(github.Auth())
private.GET("/", UserInfoHandler)
private.GET("/api", func(ctx *gin.Context) {
	ctx.JSON(200, gin.H{"message": "Hello from private for groups"})
})

router.Run("127.0.0.1:8081")

A handler will fetch user information from the gin.Context that's stored in github.Auth.

    func UserInfoHandler(ctx *gin.Context) {
        ctx.JSON(http.StatusOK, gin.H{"Hello": "from private", "user": ctx.MustGet("user")})
    }

Testing GitHub Auth

  • Created your GitHub clientid stored in clientid.github.json similar to and grant redirect to example/github/test-clientid.github.json, get this from your GitHub application.
  • run the server: % go run example/github/github.go -cred-file clientid.github.json
  • open http://127.0.0.1:8081/login in your browser
  • In your browser, follow the login, and choose your identity to login with
  • You'll be redirected to the http://127.0.0.1:8081/auth endpoint, which should show your identity data

Contributing/TODO

We welcome contributions from the community; just submit a pull request. To help you get started, here are some items that we'd love help with:

  • Adding automated tests, possibly with dex, to include Travis CI in the setup
  • Adding integration with other open-source token providers
  • Refactoring and rebuilding a customizable Google LoginHandler
  • Adding other OAuth2 providers like Google and GitHub
  • The code base

Please use GitHub issues as the starting point for contributions, new ideas and/or bug reports.

Contact

Contributors

Thanks to:

  • Olivier MenguΓ©
  • Josta Yee

License

See LICENSE file.

More Repositories

1

patroni

A template for PostgreSQL High Availability with Etcd, Consul, ZooKeeper, or Kubernetes
Python
6,267
star
2

postgres-operator

Postgres operator creates and manages PostgreSQL clusters running in Kubernetes
Go
3,686
star
3

skipper

An HTTP router and reverse proxy for service composition, including use cases like Kubernetes Ingress
Go
3,088
star
4

restful-api-guidelines

A model set of guidelines for RESTful APIs and Events, created by Zalando
CSS
2,605
star
5

zalenium

A flexible and scalable container based Selenium Grid with video recording, live preview, basic auth & dashboard.
Java
2,385
star
6

SwiftMonkey

A framework for doing randomised UI testing of iOS apps
Swift
1,947
star
7

logbook

An extensible Java library for HTTP request and response logging
Java
1,788
star
8

tailor

A streaming layout service for front-end microservices
JavaScript
1,728
star
9

tech-radar

Visualizing our technology choices
1,581
star
10

spilo

Highly available elephant herd: HA PostgreSQL cluster using Docker
Python
1,225
star
11

intellij-swagger

A plugin to help you easily edit Swagger and OpenAPI specification files inside IntelliJ IDEA
Java
1,172
star
12

problem-spring-web

A library for handling Problems in Spring Web MVC
Java
1,031
star
13

nakadi

A distributed event bus that implements a RESTful API abstraction on top of Kafka-like queues
Java
928
star
14

zally

A minimalistic, simple-to-use API linter
Kotlin
903
star
15

problem

A Java library that implements application/problem+json
Java
869
star
16

zalando-howto-open-source

Open Source guidance from Zalando, Europe's largest online fashion platform
799
star
17

go-keyring

Cross-platform keyring interface for Go
Go
689
star
18

zappr

An agent that enforces guidelines for your GitHub repositories
JavaScript
542
star
19

pg_view

Get a detailed, real-time view of your PostgreSQL database and system metrics
Python
494
star
20

engineering-principles

Our guidelines for building new applications and managing legacy systems
376
star
21

gulp-check-unused-css

A build tool for checking your HTML templates for unused CSS classes
CSS
359
star
22

zmon

Real-time monitoring of critical metrics & KPIs via elegant dashboards, Grafana3 visualizations & more
Shell
355
star
23

expan

Open-source Python library for statistical analysis of randomised control trials (A/B tests)
Python
325
star
24

PGObserver

A battle-tested, flexible & comprehensive monitoring solution for your PostgreSQL databases
Python
316
star
25

riptide

Client-side response routing for Spring
Java
292
star
26

jackson-datatype-money

Extension module to properly support datatypes of javax.money
Java
240
star
27

grafter

Grafter is a library to configure and wire Scala applications
Scala
240
star
28

opentracing-toolbox

Best-of-breed OpenTracing utilities, instrumentations and extensions
Java
180
star
29

elm-street-404

A fun WebGL game built with Elm
Elm
176
star
30

tokens

Java library for conveniently verifying and storing OAuth 2.0 service access tokens
Java
169
star
31

innkeeper

Simple route management API for Skipper
Scala
166
star
32

public-presentations

List of public talks by Zalando Tech: meetup presentations, recorded conference talks, slides
165
star
33

python-nsenter

Enter kernel namespaces from Python
Python
139
star
34

faux-pas

A library that simplifies error handling for Functional Programming in Java
Java
132
star
35

dress-code

The official style guide and framework for all Zalando Brand Solutions products
CSS
129
star
36

beard

A lightweight, logicless templating engine, written in Scala and inspired by Mustache
Scala
121
star
37

friboo

Utility library for writing microservices in Clojure, with support for Swagger and OAuth
Clojure
117
star
38

spring-cloud-config-aws-kms

Spring Cloud Config add-on that provides encryption via AWS KMS
Java
99
star
39

zalando.github.io

Open Source Documentation and guidelines for Zalando developers
HTML
86
star
40

failsafe-actuator

Endpoint library for the failsafe framework
Java
52
star
41

package-build

A toolset for building system packages using Docker and fpm-cookery
Ruby
35
star
42

ghe-backup

Github Enterprise backup at ZalandoTech (Kubernetes, AWS, Docker)
Shell
30
star
43

rds-health

discover anomalies, performance issues and optimization within AWS RDS
Go
26
star
44

backstage-plugin-api-linter

API Linter is a quality assurance tool that checks the compliance of API's specifications to Zalando's API rules.
TypeScript
12
star
45

.github

Standard github health files
1
star