{"id":14987633,"url":"https://github.com/zalando/gin-oauth2","last_synced_at":"2025-10-24T11:34:28.788Z","repository":{"id":37390951,"uuid":"42236431","full_name":"zalando/gin-oauth2","owner":"zalando","description":"Middleware for Gin Framework users who also want to use OAuth2","archived":false,"fork":false,"pushed_at":"2025-05-14T11:31:16.000Z","size":387,"stargazers_count":597,"open_issues_count":13,"forks_count":70,"subscribers_count":20,"default_branch":"master","last_synced_at":"2025-05-14T12:48:07.002Z","etag":null,"topics":["authentication","authorization","gin","gin-middleware","oauth2"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zalando.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2015-09-10T09:52:00.000Z","updated_at":"2025-05-14T11:31:13.000Z","dependencies_parsed_at":"2024-06-03T14:30:18.853Z","dependency_job_id":"06111562-879b-4391-bda9-20b992cf6af8","html_url":"https://github.com/zalando/gin-oauth2","commit_stats":{"total_commits":139,"total_committers":24,"mean_commits":5.791666666666667,"dds":0.7769784172661871,"last_synced_commit":"4a74dccc94ca144dc36b2af2a67d8f0fcae8ad68"},"previous_names":["zalando-techmonkeys/gin-oauth2"],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zalando%2Fgin-oauth2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zalando%2Fgin-oauth2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zalando%2Fgin-oauth2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zalando%2Fgin-oauth2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zalando","download_url":"https://codeload.github.com/zalando/gin-oauth2/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254259387,"owners_count":22040821,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","authorization","gin","gin-middleware","oauth2"],"created_at":"2024-09-24T14:15:04.796Z","updated_at":"2025-10-24T11:34:23.754Z","avatar_url":"https://github.com/zalando.png","language":"Go","funding_links":[],"categories":["Go"],"sub_categories":[],"readme":"# Gin-OAuth2\n\n[![Go Report\nCard](https://goreportcard.com/badge/zalando/gin-oauth2)](https://goreportcard.com/report/zalando/gin-oauth2)\n[![Build Status](https://github.com/zalando/gin-oauth2/actions/workflows/master.yaml/badge.svg)](https://github.com/zalando/gin-oauth2/actions/workflows/master.yaml)\n[![GoDoc](https://pkg.go.dev/badge/github.com/zalando/gin-oauth2.svg)](https://pkg.go.dev/github.com/zalando/gin-oauth2)\n\n\nGin-OAuth2 is specially made for [Gin Framework](https://github.com/gin-gonic/gin)\nusers who also want to use OAuth2. It was created by Go developers\nwho needed Gin middleware for working with OAuth2 and couldn't find\nany.\n\n## Project Context and Features\n\nWhen it comes to choosing a Go framework, there's a lot of confusion\nabout what to use. The scene is very fragmented, and detailed\ncomparisons of different frameworks are still somewhat rare. Meantime,\nhow to handle dependencies and structure projects are big topics in\nthe Go community. We've liked using Gin for its speed,\naccessibility, and usefulness in developing microservice\narchitectures. In creating Gin-OAuth2, we wanted to take fuller\nadvantage of Gin's capabilities and help other devs do likewise.\n\nGin-OAuth2 is expressive, flexible, and very easy to use. It allows you to:\n- do OAuth2 authorization based on HTTP routing\n- create router groups to place OAuth2 authorization on top, using HTTP verbs and passing them\n- more easily decouple services by promoting a \"say what to do, not how to do it\" approach\n- configure your REST API directly in the code (see the \"Usage\" example below)\n- write your own authorization functions\n\n## How OAuth 2 Works\n\nIf you're just starting out with OAuth2, you might find these\nresources useful:\n\n- [OAuth 2 Simplified](https://aaronparecki.com/oauth-2-simplified/)\n- [An Introduction to OAuth 2](https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2)\n\n## Requirements\n\n- [Gin](https://github.com/gin-gonic/gin)\n- An OAuth2 Token provider (we recommend that you use your own,\n  p.e. use [dex](https://github.com/coreos/dex))\n- a Tokeninfo service (p.e. use [dex](https://github.com/coreos/dex))\n\nGin-OAuth2 uses the following [Go](https://golang.org/) packages as\ndependencies:\n\n* [Gin](https://github.com/gin-gonic/gin)\n* [glog](https://github.com/golang/glog)\n* [gin-glog](https://github.com/szuecs/gin-glog)\n\n## Installation\n\nAssuming you've installed Go and Gin, run this:\n\n    go get github.com/zalando/gin-oauth2\n\n## Usage\n\n[This example](https://github.com/zalando/gin-oauth2/blob/master/example/zalando/main.go) shows you how to use Gin-OAuth2.\n\n### Uid-Based Access\n\nFirst, define your access triples to identify who has access to a\ngiven resource. This snippet shows how to grant resource access to two\nhypothetical employees:\n\n        // from zalando package\n        // type AccessTuple struct {\n        //      Realm string // p.e. \"employees\", \"services\"\n        //      Uid   string // UnixName\n        //      Cn    string // RealName\n        // }\n        var USERS []zalando.AccessTuple = []zalando.AccessTuple{\n\t    {\"/employees\", \"sszuecs\", \"Sandor Szücs\"},\n            {\"/employees\", \"njuettner\", \"Nick Jüttner\"},\n        }\n\nNext, define which Gin middlewares you use. The third line in this\nsnippet is a basic audit log:\n\n\trouter := gin.New()\n\trouter.Use(ginglog.Logger(3 * time.Second))\n\trouter.Use(ginoauth2.RequestLogger([]string{\"uid\"}, \"data\"))\n\trouter.Use(gin.Recovery())\n\nFinally, define which type of access you grant to the defined\nusers. We'll use a router group, so that we can add a bunch of router\npaths and HTTP verbs:\n\n\tprivateUser := router.Group(\"/api/privateUser\")\n\tprivateUser.Use(ginoauth2.Auth(zalando.UidCheck(USERS), zalando.OAuth2Endpoint))\n\tprivateUser.GET(\"/\", func(c *gin.Context) {\n\t\tif v, ok := c.Get(\"cn\"); ok {\n\t\t\tc.JSON(200, gin.H{\"message\": fmt.Sprintf(\"Hello from private for users to %s\", v)})\n\t\t} else {\n\t\t\tc.JSON(200, gin.H{\"message\": \"Hello from private for users without cn\"})\n\t\t}\n\t})\n\n#### Testing\n\nTo test, you can use curl:\n\n        curl -H \"Authorization: Bearer $TOKEN\" http://localhost:8081/api/privateUser/\n        {\"message\":\"Hello from private for users to Sandor Szücs\"}\n\n### Team-Based Access\n\nAs with Uid-based access, define your access triples to identify who\nhas access to a given resource. With this snippet, you can grant resource\naccess to an entire team instead of individuals:\n\n        var TEAMS []zalando.AccessTuple = []zalando.AccessTuple{\n\t    {\"teams\", \"opensourceguild\", \"OpenSource Guild\"},\n\t    {\"teams\", \"tm\", \"Platform / System\"},\n\t    {\"teams\", \"teapot\", \"Platform / Cloud API\"},\n        }\n\nNow define which Gin middlewares you use:\n\n\trouter := gin.New()\n\trouter.Use(ginglog.Logger(3 * time.Second))\n\trouter.Use(ginoauth2.RequestLogger([]string{\"uid\"}, \"data\"))\n\trouter.Use(gin.Recovery())\n\nLastly, define which type of access you grant to the defined\nteam. We'll use a router group again:\n\n\tprivateGroup := router.Group(\"/api/privateGroup\")\n\tprivateGroup.Use(ginoauth2.Auth(zalando.GroupCheck(TEAMS), zalando.OAuth2Endpoint))\n\tprivateGroup.GET(\"/\", func(c *gin.Context) {\n\t\tuid, okUid := c.Get(\"uid\")\n\t\tif team, ok := c.Get(\"team\"); ok \u0026\u0026 okUid {\n\t\t\tc.JSON(200, gin.H{\"message\": fmt.Sprintf(\"Hello from private to %s member of %s\", uid, team)})\n\t\t} else {\n\t\t\tc.JSON(200, gin.H{\"message\": \"Hello from private for groups without uid and team\"})\n\t\t}\n\t})\n\nOnce again, you can use curl to test:\n\n        curl -H \"Authorization: Bearer $TOKEN\" http://localhost:8081/api/privateGroup/\n        {\"message\":\"Hello from private to sszuecs member of teapot\"}\n\n### Run Example Service\n\nRun example service:\n\n    % go run example/zalando/main.go -v=2 -logtostderr\n    [GIN-debug] [WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n    - using env:   export GIN_MODE=release\n    - using code:  gin.SetMode(gin.ReleaseMode)\n    [GIN-debug] GET   /api/                     --\u003e main.func·001 (4 handlers)\n    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}]\n    [GIN-debug] GET   /api/private/             --\u003e main.func·002 (5 handlers)\n    I1028 10:12:44.908342   22325 main.go:41] bootstrapped application\n    [GIN-debug] Listening and serving HTTP on :8081\n    I1028 10:12:46.794502   22325 ginoauth2.go:213] Grant access to sszuecs\n    I1028 10:12:46.794571   22325 ginglog.go:93] [GIN] | 200 | 194.162911ms | [::1]:58629 |   GET     /api/private/\n\nGet an access token from your token provider (```oauth2.Endpoint.AuthURL```):\n\n    % TOKEN=$(curl https://$USER:$PASSWORD@token.oauth2.corp.com/access_token)\n\nRequest:\n\n    % curl -H \"Authorization: Bearer $TOKEN\" http://localhost:8081/api/privateGroup/\n    {\"message\":\"Hello from private to sszuecs member of teapot\"}\n\n### Google-Based Access\n\nAs shown in [this great article](http://skarlso.github.io/2016/06/12/google-signin-with-go/) about Gin and Google signin, you have to create credentials for an \"OAuth client ID.\" In your [Google Cloud Console](https://console.cloud.google.com), you will find \"Credentials\" in the \"API Manager\":\n\n![Picture of Google Cloud Console showing API Manager](https://raw.githubusercontent.com/zalando/gin-oauth2/master/doc/gcp-credentials.png)\n\nYou have to specify a path to your [clientid credential file](./example/google/test-clientid.google.json) and a slice of\nscopes that you request for authorization.\nYou have also to specify the URL to get redirected to upon completion of the Google OAuth2.\nLastly, you have to choose a secret for the CookieStore and a session.\nThis OAuth2 flow is also known as [Authorization Code Flow](https://tools.ietf.org/html/rfc6749#section-4.1).\n\n        redirectURL := \"http://127.0.0.1:8081/auth/\"\n        credFile := \"./example/google/test-clientid.google.json\" // you have to build your own\n        scopes := []string{\n               \"https://www.googleapis.com/auth/userinfo.email\",\n               // You have to select your own scope from here -\u003e https://developers.google.com/identity/protocols/googlescopes#google_sign-in\n\t}\n\tsecret := []byte(\"secret\") //\n\tsessionName := \"goquestsession\"\n\n\trouter := gin.Default()\n\t// init settings for google auth\n\tgoogle.Setup(redirectURL, credFile, scopes, secret)\n\trouter.Use(google.Session(sessionName))\n\n\nAfter the base setup, register a login handler. You might want to implement it yourself (pull requests are welcome):\n\n\trouter.GET(\"/login\", google.LoginHandler)\n\nWith 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.\"\n\n\t// protected url group\n\tprivate := router.Group(\"/auth\")\n\tprivate.Use(google.Auth())\n\tprivate.GET(\"/\", UserInfoHandler)\n\tprivate.GET(\"/api\", func(ctx *gin.Context) {\n\t\tctx.JSON(200, gin.H{\"message\": \"Hello from private for groups\"})\n\t})\n\n\trouter.Run(\"127.0.0.1:8081\")\n\nA handler will fetch user information from the gin.Context that's stored in google.Auth.\n\n        func UserInfoHandler(ctx *gin.Context) {\n\t        ctx.JSON(http.StatusOK, gin.H{\"Hello\": \"from private\", \"user\": ctx.MustGet(\"user\").(google.User)})\n        }\n\n#### Testing Google Auth\n\n- 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](http://skarlso.github.io/2016/06/12/google-signin-with-go/) mentioned before.\n- run the server: ```% go run example/google/google.go -cred-file clientid.google.json```\n- open [http://127.0.0.1:8081/login](http://127.0.0.1:8081/login) in your browser\n- In your browser, follow the login, and choose your identity to login with\n- You'll be redirected to the http://127.0.0.1:8081/auth endpoint, which should show your identity data\n\n### GitHub-Based Access\n\nAs shown in [this blog post](https://blog.kowalczyk.info/article/f/Accessing-GitHub-API-from-Go.html) about Go and GitHub signin, you have to [register your application](https://github.com/settings/applications/new) with GitHub to get an \"OAuth client ID.\" In your [developer applications](https://github.com/settings/developers), you will find your \"Credentials\":\n\nFrom this article the flow of OAuth2 is:\n\n* the user is on your website and clicks “login with GitHub” link\n* you redirect the user to GitHub’s authorization page. In that url you specify desired access level and a random secret\nthe user authorizes your app by clicking on a link\n* GitHub redirects to a callback url on your website (which you provided when registering the app with GitHub)\n* in the url handler, extract “secret” and “code” args\n* you have to check that the secret is the same as the one you sent to GitHub (security measure that prevents forgery)\n* you call another GitHub url to exchange code for access token\n\nYou have to specify a path to your [clientid credential file](./example/github/test-clientid.github.json) and a slice of\nscopes that you request for authorization.\nYou have also to specify the URL to get redirected to upon completion of the GitHub OAuth2.\nLastly, you have to choose a secret for the CookieStore and a session.\nThis OAuth2 flow is also known as [Authorization Code Flow](https://tools.ietf.org/html/rfc6749#section-4.1).\n\n        redirectURL := \"http://127.0.0.1:8081/auth/\"\n        credFile := \"./example/github/test-clientid.github.json\" // you have to build your own\n        scopes := []string{\n               \"repo\",\n               // You have to select your own scope from here -\u003e https://developer.github.com/v3/oauth/#scopes\n\t}\n\tsecret := []byte(\"secret\") //\n\tsessionName := \"goquestsession\"\n\n\trouter := gin.Default()\n\t// init settings for github auth\n\tgithub.Setup(redirectURL, credFile, scopes, secret)\n\trouter.Use(github.Session(sessionName))\n\n\nAfter the base setup, register a login handler. You might want to implement it yourself (pull requests are welcome):\n\n\trouter.GET(\"/login\", github.LoginHandler)\n\nWith 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.\"\n\n\t// protected url group\n\tprivate := router.Group(\"/auth\")\n\tprivate.Use(github.Auth())\n\tprivate.GET(\"/\", UserInfoHandler)\n\tprivate.GET(\"/api\", func(ctx *gin.Context) {\n\t\tctx.JSON(200, gin.H{\"message\": \"Hello from private for groups\"})\n\t})\n\n\trouter.Run(\"127.0.0.1:8081\")\n\nA handler will fetch user information from the gin.Context that's stored in github.Auth.\n\n        func UserInfoHandler(ctx *gin.Context) {\n\t        ctx.JSON(http.StatusOK, gin.H{\"Hello\": \"from private\", \"user\": ctx.MustGet(\"user\")})\n        }\n\n#### Testing GitHub Auth\n\n- 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](https://github.com/settings/applications).\n- run the server: ```% go run example/github/github.go -cred-file clientid.github.json```\n- open [http://127.0.0.1:8081/login](http://127.0.0.1:8081/login) in your browser\n- In your browser, follow the login, and choose your identity to login with\n- You'll be redirected to the http://127.0.0.1:8081/auth endpoint, which should show your identity data\n\n## Contributing/TODO\n\nWe 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:\n\n- Adding automated tests, possibly with\n  [dex](https://github.com/coreos/dex), to include Travis CI in the\n  setup\n- Adding integration with other open-source token providers\n- Refactoring and rebuilding a customizable Google LoginHandler\n- Adding other OAuth2 providers like Google and GitHub\n- The code base\n\nPlease use GitHub issues as the starting point for contributions, new ideas and/or bug reports.\n\n## Contact\n\n* E-Mail: team-teapot@zalando.de\n* Security issues: Please send an email to\n  [maintainers](MAINTAINERS). We'll try to get back to you within two\n  workdays. If you don't hear back ,then send an email to team-teapot@zalando.de.\n\n## Contributors\n\nThanks to:\n\n- Olivier Mengué\n- Josta Yee\n\n## License\n\nSee [LICENSE](LICENSE) file.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzalando%2Fgin-oauth2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzalando%2Fgin-oauth2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzalando%2Fgin-oauth2/lists"}