{"id":22044744,"url":"https://github.com/nilorg/oauth2","last_synced_at":"2025-05-08T05:43:05.130Z","repository":{"id":57488424,"uuid":"203628375","full_name":"nilorg/oauth2","owner":"nilorg","description":"Go OAuth2 Server/Client library","archived":false,"fork":false,"pushed_at":"2025-04-20T05:00:02.000Z","size":186,"stargazers_count":13,"open_issues_count":0,"forks_count":2,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-04-20T05:26:47.745Z","etag":null,"topics":["go","go-oauth2","go-oauth2-client","go-oauth2-server","golang","oauth2","oauth2-client","oauth2-server"],"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/nilorg.png","metadata":{"files":{"readme":"README.md","changelog":null,"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}},"created_at":"2019-08-21T17:00:09.000Z","updated_at":"2025-04-20T04:59:59.000Z","dependencies_parsed_at":"2025-04-20T05:34:29.391Z","dependency_job_id":null,"html_url":"https://github.com/nilorg/oauth2","commit_stats":null,"previous_names":[],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilorg%2Foauth2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilorg%2Foauth2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilorg%2Foauth2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilorg%2Foauth2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nilorg","download_url":"https://codeload.github.com/nilorg/oauth2/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253009534,"owners_count":21839712,"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":["go","go-oauth2","go-oauth2-client","go-oauth2-server","golang","oauth2","oauth2-client","oauth2-server"],"created_at":"2024-11-30T13:07:51.897Z","updated_at":"2025-05-08T05:43:05.098Z","avatar_url":"https://github.com/nilorg.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# oauth2\n\n# Usage\n```bash\ngo get -u github.com/nilorg/oauth2\n```\n# Import\n```bash\nimport \"github.com/nilorg/oauth2\"\n```\n\n# 例子\n\n[oauth2-server](https://github.com/nilorg/oauth2-server)\n\n[server/client](https://github.com/nilorg/oauth2/tree/master/examples)\n\n# 文档参考\n1. [《理解OAuth 2.0》阮一峰](http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)\n2. [《RFC 6749》](https://tools.ietf.org/html/rfc6749) | [《RFC 6749》](http://www.rfcreader.com/#rfc6749)\n3. [《OAuth 2.0 Device Authorization Grant(RFC8628)》](https://tools.ietf.org/html/rfc8628)\n4. [《OAuth 2.0 Token Introspection(RFC7662)》](https://tools.ietf.org/html/rfc7662)\n5. [《OAuth 2.0 Token Revocation(RFC7009)》](https://tools.ietf.org/html/rfc7009)\n\n\n### AuthorizationCode\n授权码模式（authorization code）是功能最完整、流程最严密的授权模式。\n\n它的特点就是通过客户端的后台服务器，与\"服务提供商\"的认证服务器进行互动。\n### Implicit\n简化模式（implicit grant type）不通过第三方应用程序的服务器，直接在浏览器中向认证服务器申请令牌，跳过了\"授权码\"这个步骤，因此得名。\n\n所有步骤在浏览器中完成，令牌对访问者是可见的，且客户端不需要认证。\n### ResourceOwnerPasswordCredentials\n密码模式（Resource Owner Password Credentials Grant）中，用户向客户端提供自己的用户名和密码。\n\n客户端使用这些信息，向\"服务商提供商\"索要授权。\n\n在这种模式中，用户必须把自己的密码给客户端，但是客户端不得储存密码。\n\n这通常用在用户对客户端高度信任的情况下，比如客户端是操作系统的一部分，或者由一个著名公司出品。\n\n而认证服务器只有在其他授权模式无法执行的情况下，才能考虑使用这种模式。\n### ClientCredentials\n客户端模式（Client Credentials Grant）指客户端以自己的名义，而不是以用户的名义，向\"服务提供商\"进行认证。\n\n严格地说，客户端模式并不属于OAuth框架所要解决的问题。\n\n在这种模式中，用户直接向客户端注册，客户端以自己的名义要求\"服务提供商\"提供服务，其实不存在授权问题。\n\n### DeviceCode\n设备模式（Device Code）\n\n### TokenIntrospection\n内省端点（Token Introspection）\n### TokenRevocation\nToken销毁端点（Token Revocation）\n\n# Server\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/nilorg/oauth2\"\n)\n\nvar (\n\tclients = map[string]string{\n\t\t\"oauth2_client\": \"password\",\n\t}\n)\n\nfunc main() {\n\tsrv := oauth2.NewServer()\n\tsrv.VerifyClient = func(basic *oauth2.ClientBasic) (err error) {\n\t\tpwd, ok := clients[basic.ID]\n\t\tif !ok {\n\t\t\terr = oauth2.ErrInvalidClient\n\t\t\treturn\n\t\t}\n\t\tbasic = \u0026oauth2.ClientBasic{\n\t\t\tID:     basic.ID,\n\t\t\tSecret: pwd,\n\t\t}\n\t\treturn\n\t}\n\tsrv.VerifyClientID = func(clientID string) (err error) {\n\t\t_, ok := clients[clientID]\n\t\tif !ok {\n\t\t\terr = oauth2.ErrInvalidClient\n\t\t}\n\t\treturn\n\t}\n\tsrv.VerifyCode = func(code, clientID, redirectURI string) (value *oauth2.CodeValue, err error) {\n\t\t//err = oauth2.ErrUnauthorizedClient\n\t\t// 查询缓存/数据库中的code信息\n\t\tvalue = \u0026oauth2.CodeValue{\n\t\t\tClientID:    clientID,\n\t\t\tRedirectURI: redirectURI,\n\t\t\tScope:       []string{\"a\", \"b\", \"c\"},\n\t\t}\n\t\treturn\n\t}\n\tsrv.GenerateCode = func(clientID, openID, redirectURI string, scope []string) (code string, err error) {\n\t\tcode = oauth2.RandomCode()\n\t\treturn\n\t}\n\tsrv.VerifyRedirectURI = func(clientID, redirectURI string) (err error) {\n\t\tfmt.Println(clientID)\n\t\tfmt.Println(redirectURI)\n\t\t// err = oauth2.ErrInvalidRedirectURI\n\t\treturn\n\t}\n\n\tsrv.VerifyPassword = func(username, password string) (openID string, err error) {\n\t\tif username != \"a\" || password != \"b\" {\n\t\t\terr = oauth2.ErrUnauthorizedClient\n\t\t\treturn\n\t\t}\n\t\topenID = \"xxxx\"\n\t\treturn\n\t}\n\n\tsrv.VerifyScope = func(scopes []string, clientID string) (err error) {\n\t\t// err = oauth2.ErrInvalidScope\n\t\treturn\n\t}\n\n\tsrv.GenerateAccessToken = oauth2.NewDefaultGenerateAccessToken([]byte(\"xxxxx\"))\n\tsrv.RefreshAccessToken = oauth2.NewDefaultRefreshAccessToken([]byte(\"xxxxx\"))\n\tsrv.ParseAccessToken = oauth2.NewDefaultParseAccessToken([]byte(\"xxxxx\"))\n\n\tsrv.GenerateDeviceAuthorization = func(issuer, verificationURI, clientID, scope string) (resp *oauth2.DeviceAuthorizationResponse, err error) {\n\t\tresp = \u0026oauth2.DeviceAuthorizationResponse{\n\t\t\tDeviceCode:            oauth2.RandomCode(),\n\t\t\tUserCode:              oauth2.RandomUserCode(),\n\t\t\tVerificationURI:       verificationURI,\n\t\t\tVerificationURIQrcode: \"\",\n\t\t\tExpiresIn:             0,\n\t\t\tInterval:              5,\n\t\t}\n\t\treturn\n\t}\n\n\tsrv.VerifyDeviceCode = func(deviceCode, clientID string) (value *oauth2.DeviceCodeValue, err error) {\n\t\t// err = oauth2.ErrAuthorizationPending\n\t\treturn\n\t}\n\n\tsrv.Init()\n\n\t// =============Http Default=============\n\t// http.HandleFunc(\"/authorize\", srv.HandleAuthorize)\n\t// http.HandleFunc(\"/token\", srv.HandleToken)\n\t// if err := http.ListenAndServe(\":8003\", srv); err != nil {\n\t// \tfmt.Printf(\"%+v\\n\", err)\n\t// }\n\n\t// =============Gin=============\n\tr := gin.Default()\n\toauth2Group := r.Group(\"/oauth2\")\n\t{\n\t\toauth2Group.GET(\"/authorize\", func(c *gin.Context) {\n\t\t\tsrv.HandleAuthorize(c.Writer, c.Request)\n\t\t})\n\t\toauth2Group.POST(\"/token\", func(c *gin.Context) {\n\t\t\tsrv.HandleToken(c.Writer, c.Request)\n\t\t})\n\t\toauth2Group.POST(\"/device_authorization\", func(c *gin.Context) {\n\t\t\tsrv.HandleDeviceAuthorization(c.Writer, c.Request)\n\t\t})\n\t}\n\n\tif err := http.ListenAndServe(\":8003\", r); err != nil {\n\t\tfmt.Printf(\"%+v\\n\", err)\n\t}\n}\n```\n\n# Client\n\n```go\npackage main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/nilorg/oauth2\"\n\t\"github.com/nilorg/pkg/logger\"\n)\n\nvar (\n\tclient *oauth2.Client\n)\n\nfunc init()  {\n\tlogger.Init()\n\tclient = oauth2.NewClient(\"http://localhost:8003\", \"oauth2_client\", \"password\")\n\tclient.Log = logger.Default()\n}\nfunc main() {\n\tr := gin.Default()\n\tr.GET(\"/ping\", func(c *gin.Context) {\n\t\t//err := client.AuthorizeImplicit(c.Writer, \"http://localhost:8080/callback\", \"test\", \"aaaaa\")\n\t\t//if err != nil {\n\t\t//\tlogger.Errorln(err)\n\t\t//\treturn\n\t\t//}\n\t\terr := client.AuthorizeAuthorizationCode(c.Writer, \"http://localhost:8080/callback\", \"test\", \"bbbbb\")\n\t\tif err != nil {\n\t\t\tlogger.Errorln(err)\n\t\t\treturn\n\t\t}\n\t})\n\tr.GET(\"/callback\", func(c *gin.Context) {\n\t\tcode := c.Query(\"code\")\n\t\tstate := c.Query(\"state\")\n\t\ttoken, err := client.TokenAuthorizationCode(code, c.Request.URL.String(), state)\n\t\tif err != nil {\n\t\t\tc.JSON(200, gin.H{\n\t\t\t\t\"message\": \"callback\",\n\t\t\t\t\"err\":     err.Error(),\n\t\t\t})\n\t\t} else {\n\t\t\tc.JSON(200, gin.H{\n\t\t\t\t\"message\": \"callback\",\n\t\t\t\t\"token\":   token,\n\t\t\t})\n\t\t}\n\t})\n\n\tr.Run() // listen and serve on 0.0.0.0:8080\n}\n```\n\n# jwt playload\n \n 标准中注册的声明 (建议但不强制使用) ：\n \n `iss`: 令牌**颁发者**。它表示**该令牌是由谁创建的**，在好很多OAuth部署中会将它设为授权服务器的URL。该声明是一个字符串\n \n `sub`: 令牌的**主体**。它表示**该令牌是关于谁的**，在很多OAuth部署中会将它设为资源拥有者的唯一标识。在大多数情况下，主题在同一个颁发者的范围内必须是唯一的。该声明是一个字符串\n \n `aud`: 令牌的**受众**。它表示**令牌的接收者**，在很多OAuth部署中，它包含受保护资源的URI或者能够接收该令牌的受保护资源。该声明可以是一个字符串数组，如果只有一个值，也可以是一个不用数组包装的单个字符串\n \n `exp`: 令牌的**过期**时间戳。它表示**令牌将在何时过期**，以便部署应用让令牌自行失效。该声明是一个整数，表示自UNIX新世纪（即格林威治标准时间GMT，1970年1月1日零点）以来的秒数\n \n `nbf`: 令牌的**生效**时的时间戳。它表示**令牌从什么时候开始生效**，以便部署应用可以在令牌生效之前颁发令牌。该声明是一个整数，表示自UNIX新世纪（即格林威治标准时间GMT，1970年1月1日零点）以来的秒数\n \n `iat`: 令牌**颁发时**的时间戳。它表示**令牌是何时被创建的**，它通常是颁发者在生成令牌时的系统时间戳。该声明是一个整数，表示自UNIX新世纪（即格林威治标准时间GMT，1970年1月1日零点）以来的秒数\n \n `jti`: 令牌的**唯一标识符**。该声明的值**在令牌颁发者创建的每个令牌中都是唯一的**，为了防止冲突，它通常是一个密码学随机值。这个值相当于向结构化令牌中加入了一个攻击者无法获得的随机熵组件，有利于防止令牌猜测攻击和重放攻击\n\n ---\n \n 公共的声明 ：\n 公共的声明可以添加任何的信息，一般添加用户的相关信息或其他业务需要的必要信息.但不建议添加敏感信息，因为该部分在客户端可解密.\n \n 私有的声明 ：\n 私有声明是提供者和消费者所共同定义的声明，一般不建议存放敏感信息，因为base64是对称解密的，意味着该部分信息可以归类为明文信息。","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilorg%2Foauth2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnilorg%2Foauth2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilorg%2Foauth2/lists"}