{"id":20554926,"url":"https://github.com/vodolaz095/ldap4gin","last_synced_at":"2025-04-14T12:43:08.527Z","repository":{"id":57580493,"uuid":"361411190","full_name":"vodolaz095/ldap4gin","owner":"vodolaz095","description":"Authenticator for gin framework using ldap server","archived":false,"fork":false,"pushed_at":"2024-12-30T11:59:53.000Z","size":363,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-27T15:56:19.813Z","etag":null,"topics":["gin-framework","gin-gonic","golang","ldap","ldap-authentication","session-management","sessions"],"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/vodolaz095.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","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},"funding":{"custom":["https://www.tinkoff.ru/rm/ostroumov.anatoliy2/4HFzm76801/"]}},"created_at":"2021-04-25T11:36:23.000Z","updated_at":"2024-12-30T11:59:05.000Z","dependencies_parsed_at":"2022-09-19T09:50:37.350Z","dependency_job_id":"d5c8b971-2559-4244-bc84-88c96d755257","html_url":"https://github.com/vodolaz095/ldap4gin","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vodolaz095%2Fldap4gin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vodolaz095%2Fldap4gin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vodolaz095%2Fldap4gin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vodolaz095%2Fldap4gin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vodolaz095","download_url":"https://codeload.github.com/vodolaz095/ldap4gin/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248883235,"owners_count":21177184,"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":["gin-framework","gin-gonic","golang","ldap","ldap-authentication","session-management","sessions"],"created_at":"2024-11-16T03:14:32.996Z","updated_at":"2025-04-14T12:43:08.506Z","avatar_url":"https://github.com/vodolaz095.png","language":"Go","funding_links":["https://www.tinkoff.ru/rm/ostroumov.anatoliy2/4HFzm76801/"],"categories":[],"sub_categories":[],"readme":"# ldap4gin\nAuthenticator for gin framework using ldap server\n\n[![Go Report Card](https://goreportcard.com/badge/github.com/vodolaz095/ldap4gin)](https://goreportcard.com/report/github.com/vodolaz095/ldap4gin)\n[![GoDoc](https://pkg.go.dev/badge/github.com/vodolaz095/ldap4gin?status.svg)](https://pkg.go.dev/github.com/vodolaz095/ldap4gin?tab=doc)\n\n\n# Advertisement\nYou can support development of this module by sending me money directly\nhttps://www.tinkoff.ru/rm/ostroumov.anatoliy2/4HFzm76801/\n\n# Installing\n\nUsual way for go module\n\n```shell\n\ngo get -u github.com/vodolaz095/ldap4gin\n\n```\n\nCode was tested against popular [osixia/openldap:1.4.0](https://hub.docker.com/r/osixia/openldap) container,\nwith records generated using [ldapaccountmanager/lam](https://hub.docker.com/r/ldapaccountmanager/lam) web ui.\n\n# Example\nWorking example is published in `example/` subdirectory of this repo.\nIn order to get working ldap server you need to start it with\n[docker compose up -d](https://docs.docker.com/compose/install/) and then edit users and groups in \n[LDAP Account Manager](https://github.com/LDAPAccountManager/lam) on http://127.0.0.1:8085/lam/templates/login.php\n\n```go\n\npackage main\n\nimport (\n   \"bytes\"\n   \"crypto/tls\"\n   \"fmt\"\n   \"log\"\n   \"net/http\"\n   \"time\"\n\n   \"github.com/gin-contrib/sessions\"\n   \"github.com/gin-contrib/sessions/cookie\"\n   \"github.com/gin-gonic/gin\"\n   \"github.com/vodolaz095/ldap4gin\"\n)\n\nfunc main() {\n   r := gin.Default()\n   r.LoadHTMLGlob(\"views/*\")\n   // configuring options used to connect to LDAP database\n   authenticator, err := ldap4gin.New(\u0026ldap4gin.Options{\n      Debug: gin.IsDebugging(),\n\n      ConnectionString: \"ldap://127.0.0.1:389\",\n      ReadonlyDN:       \"cn=readonly,dc=vodolaz095,dc=life\",\n      ReadonlyPasswd:   \"readonly\",\n      TLS:              \u0026tls.Config{}, // nearly sane default values\n      StartTLS:         false,\n\n      UserBaseTpl: \"uid=%s,ou=people,dc=vodolaz095,dc=life\",\n      ExtraFields: []string{\"l\"}, // get location too\n\n      ExtractGroups: true,\n      GroupsOU:      \"ou=groups,dc=vodolaz095,dc=life\",\n\n      TTL: 10 * time.Second,\n   })\n   if err != nil {\n      log.Fatalf(\"%s : while initializing ldap4gin authenticator\", err)\n   }\n   log.Println(\"LDAP server dialed!\")\n   defer authenticator.Close()\n   // Application should use any of compatible sessions offered by\n   // https://github.com/gin-contrib/sessions module\n   // CAUTION: secure cookie session storage has limits on user profile size!!!\n   store := cookie.NewStore([]byte(\"secret\"))\n   r.Use(sessions.Sessions(\"mysession\", store))\n\n   // dashboard\n   r.GET(\"/\", func(c *gin.Context) {\n      session := sessions.Default(c)\n      flashes := session.Flashes()\n      defer session.Save()\n      //  extracting user's profile from context\n      user, err := authenticator.Extract(c)\n      if err != nil {\n         if err.Error() == \"unauthorized\" { // render login page\n            c.HTML(http.StatusUnauthorized, \"unauthorized.html\", gin.H{\n               \"flashes\": flashes,\n            })\n            return\n         }\n         if err.Error() == \"malformed username\" {\n            session.AddFlash(\"Malformed username\")\n            c.HTML(http.StatusUnauthorized, \"unauthorized.html\", gin.H{\n               \"flashes\": flashes,\n            })\n            return\n         }\n         panic(err) // something wrong, like LDAP server stopped\n      }\n      // We can extract extra attributes for user using `user.Entry`\n      buff := bytes.NewBuffer(nil)\n      fmt.Fprintf(buff, \"DN: %s\\n\", user.Entry.DN)\n      for _, attr := range user.Entry.Attributes {\n         fmt.Fprintf(buff, \"%s: %s\\n\", attr.Name, attr.Values)\n      }\n      c.HTML(http.StatusOK, \"profile.html\", gin.H{\n         \"user\":    user,\n         \"flashes\": flashes,\n         \"raw\":     buff.String(),\n      })\n   })\n\n   // route to authorize user by username and password\n   r.POST(\"/login\", func(c *gin.Context) {\n      session := sessions.Default(c)\n      defer session.Save()\n      username := c.PostForm(\"username\")\n      password := c.PostForm(\"password\")\n      log.Printf(\"User %s tries to authorize from %s...\", username, c.ClientIP())\n      err := authenticator.Authorize(c, username, password)\n      if err != nil {\n         log.Printf(\"User %s failed to authorize from %s because of %s\", username, c.ClientIP(), err.Error())\n         session.AddFlash(fmt.Sprintf(\"Authorization error  %s\", err))\n         c.Redirect(http.StatusFound, \"/\")\n         return\n      } else {\n         log.Printf(\"User %s authorized from %s!\", username, c.ClientIP())\n         session.AddFlash(fmt.Sprintf(\"Welcome, %s!\", username))\n      }\n      user, err := authenticator.Extract(c)\n      if err != nil {\n         log.Printf(\"%s : while extracting user\", err)\n      } else {\n         log.Printf(\"user %s is extracted\", user.DN)\n      }\n      c.Redirect(http.StatusFound, \"/\")\n   })\n\n   // route to terminate session and perform logout\n   r.GET(\"/logout\", func(c *gin.Context) {\n      authenticator.Logout(c)\n      c.Redirect(http.StatusFound, \"/\")\n   })\n\n   err = r.Run(\"0.0.0.0:3000\")\n   if err != nil {\n      log.Fatalf(\"%s : while starting application\", err)\n   }\n}\n\n```\n\nHow it works?\n============================\n\nYou can read [very good article in Russian language describing authentication process via LDAP](https://vodolaz095.ru/nodejs-openldap/).\n\nShortly, these steps are performed in this module:\n\n1. we build DN using `username` parameter provided and `UserBaseTpl` of options\n\n```go\n\n    authenticator, err := ldap4gin.New(ldap4gin.Options{\n        Debug:            gin.IsDebugging(),\n        ConnectionString: \"ldap://127.0.0.1:389\",\n        UserBaseTpl:      \"uid=%s,ou=people,dc=vodolaz095,dc=life\",\n        TLS:              \u0026tls.Config{}, // nearly sane default values\n        StartTLS:         false,\n        ExtraFields:      []string{\"l\"}, // get location too\n    })\n\n    // some code\n\n    // in gin handler\n    err = authenticator.Authorize(c, username, password)\n\n```\n\n  like this: `uid=vodolaz095,ou=people,dc=vodolaz095,dc=life`.\n\n2. we try to perform bind using `DN` and `password`\n\n```go\n\n    authenticator.LDAPConn.Bind(dn, password)\n\n```\n\n3. if we succeeded, it means user provided good password, and we can try to extract user profile calling this query:\n\n```go\n\nsearchRequest := ldap.NewSearchRequest(\n    dn,                                // base DN\n    ldap.ScopeBaseObject,              // scope\n    ldap.NeverDerefAliases,            // DerefAliases\n    0,                                 // size limit\n    timeout,                           // timeout\n    false,                             // types only\n    fmt.Sprintf(\"(uid=%s)\", username), // filter\n    a.fields,                          // fields\n    nil,                               // controls\n)\n\n\n```\n\n4. After we extract data, we marshal it in User object, and store it in session using `gob` encoding. Its is worth notice\n   that sometimes profile size is too big for session storage, and it can be wise not to store all users fields in session\n\n5. If we enable extraction of groups by setting  `ExtractGroups:true`, we will also perform bind by specual user\n   with readonly access to all database in order to load groups of user we want to authenticate\n\n# Testing \n\n1. `docker compose up -d`\n2. Create test user account in LAM - http://127.0.0.1:8085/lam/templates/login.php, default password is `someRandomPasswordToMakeHackersSad22223338888`\n3. Set test user's username and password as environment variables `TEST_LDAP_USERNAME` and `TEST_LDAP_PASSWORD` \n4. Run tests by `make check`\n5. Run example my `make start` and try to authorize as test user\n6. Observe traces in Jaeger on http://127.0.0.1:16686/ for app `ldap4gin_example`\n\n![spans.png](docs%2Fspans.png)\n\n# MIT License\n\nCopyright (c) 2021 Anatolij Ostroumov\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvodolaz095%2Fldap4gin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvodolaz095%2Fldap4gin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvodolaz095%2Fldap4gin/lists"}