{"id":13408663,"url":"https://github.com/dghubble/gologin","last_synced_at":"2025-05-13T23:05:37.001Z","repository":{"id":37445336,"uuid":"37897520","full_name":"dghubble/gologin","owner":"dghubble","description":"Go login handlers for authentication providers (OAuth1, OAuth2)","archived":false,"fork":false,"pushed_at":"2025-05-13T19:42:21.000Z","size":586,"stargazers_count":1902,"open_issues_count":0,"forks_count":142,"subscribers_count":27,"default_branch":"main","last_synced_at":"2025-05-13T20:57:29.008Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":false,"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/dghubble.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["dghubble"]}},"created_at":"2015-06-23T04:40:52.000Z","updated_at":"2025-05-13T19:42:24.000Z","dependencies_parsed_at":"2023-02-17T07:15:41.302Z","dependency_job_id":"df661387-2b03-4a10-a511-269db408ae1d","html_url":"https://github.com/dghubble/gologin","commit_stats":{"total_commits":309,"total_committers":12,"mean_commits":25.75,"dds":"0.42071197411003236","last_synced_commit":"f1080db97bb63595ae266fcc2e661859dcb316a6"},"previous_names":["dghubble/go-login"],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dghubble%2Fgologin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dghubble%2Fgologin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dghubble%2Fgologin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dghubble%2Fgologin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dghubble","download_url":"https://codeload.github.com/dghubble/gologin/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254040697,"owners_count":22004594,"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":[],"created_at":"2024-07-30T20:00:54.442Z","updated_at":"2025-05-13T23:05:31.990Z","avatar_url":"https://github.com/dghubble.png","language":"Go","funding_links":["https://github.com/sponsors/dghubble"],"categories":["Authentication and Authorization","Authentication and OAuth","Go","身份验证和OAuth","Authentication \u0026 OAuth","Uncategorized","认证和OAuth授权","身份认证与 OAuth","\u003cspan id=\"身份验证和oauth-authentication-and-auth\"\u003e身份验证和OAuth Authentication and Auth\u003c/span\u003e"],"sub_categories":["Contents"],"readme":"# gologin\n[![GoDoc](https://pkg.go.dev/badge/github.com/dghubble/gologin.svg)](https://pkg.go.dev/github.com/dghubble/gologin)\n[![Workflow](https://github.com/dghubble/gologin/actions/workflows/test.yaml/badge.svg)](https://github.com/dghubble/gologin/actions/workflows/test.yaml?query=branch%3Amain)\n[![Sponsors](https://img.shields.io/github/sponsors/dghubble?logo=github)](https://github.com/sponsors/dghubble)\n[![Mastodon](https://img.shields.io/badge/follow-news-6364ff?logo=mastodon)](https://fosstodon.org/@dghubble)\n\n\u003cimg align=\"right\" src=\"https://storage.googleapis.com/dghubble/gologin.png\"\u003e\n\nPackage `gologin` provides chainable login `http.Handler`'s for [Google](http://godoc.org/github.com/dghubble/gologin/google), [GitHub](http://godoc.org/github.com/dghubble/gologin/github), [Twitter](http://godoc.org/github.com/dghubble/gologin/twitter), [Facebook](http://godoc.org/github.com/dghubble/gologin/facebook), [Bitbucket](http://godoc.org/github.com/dghubble/gologin/bitbucket), [Tumblr](http://godoc.org/github.com/dghubble/gologin/tumblr), or any [OAuth1](http://godoc.org/github.com/dghubble/gologin/oauth1) or [OAuth2](http://godoc.org/github.com/dghubble/gologin/oauth2) authentication providers.\n\nChoose a subpackage. Register the `LoginHandler` and `CallbackHandler` for web logins or the `TokenHandler` for (mobile) token logins. Get the authenticated user or access token from the request `context`.\n\nSee [examples](examples) for tutorials with apps you can run from the command line.\n\n## Features\n\n* `LoginHandler` and `CallbackHandler` support web login flows\n* `TokenHandler` supports native mobile token login flows\n* Obtain the user or access token from the `context`\n* Configurable OAuth 2 state parameter handling (CSRF protection)\n* Configurable OAuth 1 request secret handling\n\n## Docs\n\nRead [GoDoc](https://godoc.org/github.com/dghubble/gologin) or check the [examples](examples).\n\n## Overview\n\nPackage `gologin` provides `http.Handler`'s which can be chained together to implement authorization flows by passing data (e.g. tokens, users) via the request context. `gologin` handlers take `success` and `failure` next `http.Handler`'s to be called when authentication succeeds or fails. Chaining allows advanced customization, if desired. Once authentication succeeds, your `success` handler will have access to the user's access token and associated User/Account.\n\n## Usage\n\nChoose a subpackage such as `github` or `twitter`. `LoginHandler` and `Callback` `http.Handler`'s chain together lower level `oauth1` or `oauth2` handlers to authenticate users and fetch the GitHub or Twitter `User`, before calling your `success` `http.Handler`.\n\nLet's walk through GitHub and Twitter web login examples.\n\n### GitHub OAuth2\n\nRegister the `LoginHandler` and `CallbackHandler` on your `http.ServeMux`.\n\n```go\nimport (\n    ...\n    \"github.com/dghubble/gologin/v2\"\n\t\"github.com/dghubble/gologin/v2/github\"\n\t\"golang.org/x/oauth2\"\n\tgithubOAuth2 \"golang.org/x/oauth2/github\"\n)\n...\n\nconfig := \u0026oauth2.Config{\n    ClientID:     \"GithubClientID\",\n    ClientSecret: \"GithubClientSecret\",\n    RedirectURL:  \"http://localhost:8080/callback\",\n    Endpoint:     githubOAuth2.Endpoint,\n}\nmux := http.NewServeMux()\nstateConfig := gologin.DebugOnlyCookieConfig\nmux.Handle(\"/login\", github.StateHandler(stateConfig, github.LoginHandler(config, nil)))\nmux.Handle(\"/callback\", github.StateHandler(stateConfig, github.CallbackHandler(config, issueSession(), nil)))\n```\n\nThe `StateHandler` checks for an OAuth2 state parameter cookie, generates a non-guessable state as a short-lived cookie if missing, and passes the state value in the ctx. The `CookieConfig` allows the cookie name or expiration (default 60 seconds) to be configured. In production, use a config like `gologin.DefaultCookieConfig` which sets *Secure* true to require cookies be sent over HTTPS. If you wish to persist state parameters a different way, you may chain your own `http.Handler`. ([info](#state-parameters))\n\nThe `github` `LoginHandler` reads the state from the ctx and redirects to the AuthURL (at github.com) to prompt the user to grant access. Passing nil for the `failure` handler just means the `DefaultFailureHandler` should be used, which reports errors. ([info](#failure-handlers))\n\nThe `github` `CallbackHandler` receives an auth code and state OAuth2 redirection, validates the state against the state in the ctx, and exchanges the auth code for an OAuth2 Token. The `github` CallbackHandler wraps the lower level `oauth2` `CallbackHandler` to further use the Token to obtain the GitHub `User` before calling through to the success or failure handlers.\n\n\u003cimg src=\"https://storage.googleapis.com/dghubble/gologin-github.png\"\u003e\n\nNext, write the success `http.Handler` to do something with the Token and GitHub User added to the `ctx`.\n\n```go\nfunc issueSession() http.Handler {\n    fn := func(w http.ResponseWriter, req *http.Request) {\n        ctx := req.Context()\n        token, _ := oauth2Login.TokenFromContext(ctx)\n        githubUser, err := github.UserFromContext(ctx)\n        // handle errors and grant the visitor a session (cookie, token, etc.)\n    }\n    return http.HandlerFunc(fn)\n}\n```\n\nSee the [GitHub tutorial](examples/github) for a web app you can run from the command line.\n\n### Twitter OAuth1\n\nRegister the `LoginHandler` and `CallbackHandler` on your `http.ServeMux`.\n\n```go\nconfig := \u0026oauth1.Config{\n    ConsumerKey:    \"TwitterConsumerKey\",\n    ConsumerSecret: \"TwitterConsumerSecret\",\n    CallbackURL:    \"http://localhost:8080/callback\",\n    Endpoint:       twitterOAuth1.AuthorizeEndpoint,\n}\nmux := http.NewServeMux()\nmux.Handle(\"/login\", twitter.LoginHandler(config, nil))\nmux.Handle(\"/callback\", twitter.CallbackHandler(config, issueSession(), nil))\n```\n\nThe `twitter` `LoginHandler` obtains a request token and secret, adds them to the ctx, and redirects to the AuthorizeURL to prompt the user to grant access. Passing nil for the `failure` handler just means the `DefaultFailureHandler` should be used, which reports errors. ([info](#failure-handlers))\n\nThe `twitter` `CallbackHandler` receives an OAuth1 token and verifier, reads the request secret from the ctx, and obtains an OAuth1 access token and secret. The `twitter` CallbackHandler wraps the lower level `oauth1` CallbackHandler to further use the access token/secret to obtain the Twitter `User` before calling through to the success or failure handlers.\n\n\u003cimg src=\"https://storage.googleapis.com/dghubble/gologin-twitter.png\"\u003e\n\nNext, write the success `http.Handler` to do something with the access token/secret and Twitter User added to the `ctx`.\n\n```go\nfunc success() http.Handler {\n    fn := func(w http.ResponseWriter, req *http.Request) {\n        ctx := req.Context()\n        accessToken, accessSecret, _ := oauth1Login.AccessTokenFromContext(ctx)\n        twitterUser, err := twitter.UserFromContext(ctx)\n        // handle errors and grant the visitor a session (cookie, token, etc.)\n    }\n    return http.HandlerFunc(fn)\n}\n```\n\n*Note: Some OAuth1 providers (not Twitter), require the request secret be persisted until the callback is received. For this reason, the lower level `oauth1` package splits LoginHandler functionality into a `LoginHandler` and `AuthRedirectHandler`. Provider packages, like `tumblr`, chain these together for you, but the lower level handlers are there if needed.\n\nSee the [Twitter tutorial](examples/twitter) for a web app you can run from the command line.\n\n### State Parameters\n\nOAuth2 `StateHandler` implements OAuth 2 [RFC 6749](https://tools.ietf.org/html/rfc6749) 10.12 CSRF Protection using non-guessable values in short-lived HTTPS-only cookies to provide reasonable assurance the user in the login phase and callback phase are the same. If you wish to implement this differently, write a `http.Handler` which sets a *state* in the ctx, which is expected by LoginHandler and CallbackHandler.\n\nYou may use `oauth2.WithState(context.Context, state string)` for this. [docs](https://godoc.org/github.com/dghubble/gologin/oauth2#WithState)\n\n### Failure Handlers\n\nIf you wish to define your own failure `http.Handler`, you can get the error from the `ctx` using `gologin.ErrorFromContext(ctx)`.\n\n## Mobile\n\nTwitter includes a `TokenHandler` which can be useful for building APIs for mobile devices which use Login with Twitter.\n\n## Goals\n\nCreate small, chainable handlers to correctly implement the steps of common authentication flows. Handle provider-specific validation requirements.\n\n## Motivations\n\nPackage `gologin` implements authorization flow steps with chained handlers.\n\n* Authentication should be performed with chainable handlers to allow customization, swapping, or adding additional steps easily.\n* Authentication should be orthogonal to the session system. Let users choose their session/token library.\n* OAuth2 State CSRF should be included out of the box, but easy to customize.\n* Packages should import only what is required. OAuth1 and OAuth2 packages are separate.\n* `http.Handler` and `context` are powerful, flexible, and in the standard library.\n\nProjects [goth](https://github.com/markbates/goth) and [gomniauth](https://github.com/stretchr/gomniauth) aim to provide a similar login solution with a different design. Check them out if you decide you don't like the ideas in `gologin`.\n\n## Contributing\n\nNew auth providers can be implemented by composing the handlers in the `oauth1` or `oauth2` subpackages. See the [Contributing Guide](https://gist.github.com/dghubble/be682c123727f70bcfe7).\n\n## License\n\n[MIT License](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdghubble%2Fgologin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdghubble%2Fgologin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdghubble%2Fgologin/lists"}