ldap4gin

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2023 License: MIT Imports: 19 Imported by: 1

README

ldap4gin

Authenticator for gin framework using ldap server

Go Report Card GoDoc

Advertisement

You can support development of this module by sending me money directly https://www.tinkoff.ru/rm/ostroumov.anatoliy2/4HFzm76801/

Installing

Usual way for go module


go get -u github.com/vodolaz095/ldap4gin

Code was tested against popular osixia/openldap:1.4.0 container, with records generated using ldapaccountmanager/lam web ui.

Example

Working example is published in example/ subdirectory of this repo. In order to get working ldap server you need to start it with docker compose up -d and then edit users and groups in LDAP Account Manager on http://127.0.0.1:8085/lam/templates/login.php


package main

import (
   "bytes"
   "crypto/tls"
   "fmt"
   "log"
   "net/http"
   "time"

   "github.com/gin-contrib/sessions"
   "github.com/gin-contrib/sessions/cookie"
   "github.com/gin-gonic/gin"
   "github.com/vodolaz095/ldap4gin"
)

func main() {
   r := gin.Default()
   r.LoadHTMLGlob("views/*")
   // configuring options used to connect to LDAP database
   authenticator, err := ldap4gin.New(&ldap4gin.Options{
      Debug: gin.IsDebugging(),

      ConnectionString: "ldap://127.0.0.1:389",
      ReadonlyDN:       "cn=readonly,dc=vodolaz095,dc=life",
      ReadonlyPasswd:   "readonly",
      TLS:              &tls.Config{}, // nearly sane default values
      StartTLS:         false,

      UserBaseTpl: "uid=%s,ou=people,dc=vodolaz095,dc=life",
      ExtraFields: []string{"l"}, // get location too

      ExtractGroups: true,
      GroupsOU:      "ou=groups,dc=vodolaz095,dc=life",

      TTL: 10 * time.Second,
   })
   if err != nil {
      log.Fatalf("%s : while initializing ldap4gin authenticator", err)
   }
   log.Println("LDAP server dialed!")
   defer authenticator.Close()
   // Application should use any of compatible sessions offered by
   // https://github.com/gin-contrib/sessions module
   // CAUTION: secure cookie session storage has limits on user profile size!!!
   store := cookie.NewStore([]byte("secret"))
   r.Use(sessions.Sessions("mysession", store))

   // dashboard
   r.GET("/", func(c *gin.Context) {
      session := sessions.Default(c)
      flashes := session.Flashes()
      defer session.Save()
      //  extracting user's profile from context
      user, err := authenticator.Extract(c)
      if err != nil {
         if err.Error() == "unauthorized" { // render login page
            c.HTML(http.StatusUnauthorized, "unauthorized.html", gin.H{
               "flashes": flashes,
            })
            return
         }
         if err.Error() == "malformed username" {
            session.AddFlash("Malformed username")
            c.HTML(http.StatusUnauthorized, "unauthorized.html", gin.H{
               "flashes": flashes,
            })
            return
         }
         panic(err) // something wrong, like LDAP server stopped
      }
      // We can extract extra attributes for user using `user.Entry`
      buff := bytes.NewBuffer(nil)
      fmt.Fprintf(buff, "DN: %s\n", user.Entry.DN)
      for _, attr := range user.Entry.Attributes {
         fmt.Fprintf(buff, "%s: %s\n", attr.Name, attr.Values)
      }
      c.HTML(http.StatusOK, "profile.html", gin.H{
         "user":    user,
         "flashes": flashes,
         "raw":     buff.String(),
      })
   })

   // route to authorize user by username and password
   r.POST("/login", func(c *gin.Context) {
      session := sessions.Default(c)
      defer session.Save()
      username := c.PostForm("username")
      password := c.PostForm("password")
      log.Printf("User %s tries to authorize from %s...", username, c.ClientIP())
      err := authenticator.Authorize(c, username, password)
      if err != nil {
         log.Printf("User %s failed to authorize from %s because of %s", username, c.ClientIP(), err.Error())
         session.AddFlash(fmt.Sprintf("Authorization error  %s", err))
         c.Redirect(http.StatusFound, "/")
         return
      } else {
         log.Printf("User %s authorized from %s!", username, c.ClientIP())
         session.AddFlash(fmt.Sprintf("Welcome, %s!", username))
      }
      user, err := authenticator.Extract(c)
      if err != nil {
         log.Printf("%s : while extracting user", err)
      } else {
         log.Printf("user %s is extracted", user.DN)
      }
      c.Redirect(http.StatusFound, "/")
   })

   // route to terminate session and perform logout
   r.GET("/logout", func(c *gin.Context) {
      authenticator.Logout(c)
      c.Redirect(http.StatusFound, "/")
   })

   err = r.Run("0.0.0.0:3000")
   if err != nil {
      log.Fatalf("%s : while starting application", err)
   }
}

How it works?

You can read very good article in Russian language describing authentication process via LDAP.

Shortly, these steps are performed in this module:

  1. we build DN using username parameter provided and UserBaseTpl of options

    authenticator, err := ldap4gin.New(ldap4gin.Options{
        Debug:            gin.IsDebugging(),
        ConnectionString: "ldap://127.0.0.1:389",
        UserBaseTpl:      "uid=%s,ou=people,dc=vodolaz095,dc=life",
        TLS:              &tls.Config{}, // nearly sane default values
        StartTLS:         false,
        ExtraFields:      []string{"l"}, // get location too
    })

    // some code

    // in gin handler
    err = authenticator.Authorize(c, username, password)

like this: uid=vodolaz095,ou=people,dc=vodolaz095,dc=life.

  1. we try to perform bind using DN and password

    authenticator.LDAPConn.Bind(dn, password)

  1. if we succeeded, it means user provided good password, and we can try to extract user profile calling this query:

searchRequest := ldap.NewSearchRequest(
    dn,                                // base DN
    ldap.ScopeBaseObject,              // scope
    ldap.NeverDerefAliases,            // DerefAliases
    0,                                 // size limit
    timeout,                           // timeout
    false,                             // types only
    fmt.Sprintf("(uid=%s)", username), // filter
    a.fields,                          // fields
    nil,                               // controls
)


  1. After we extract data, we marshal it in User object, and store it in session using gob encoding. Its is worth notice that sometimes profile size is too big for session storage, and it can be wise not to store all users fields in session

  2. If we enable extraction of groups by setting ExtractGroups:true, we will also perform bind by specual user with readonly access to all database in order to load groups of user we want to authenticate

Testing

  1. docker compose up -d
  2. Create test user account in LAM - http://127.0.0.1:8085/lam/templates/login.php, default password is someRandomPasswordToMakeHackersSad22223338888
  3. Set test user's username and password as environment variables TEST_LDAP_USERNAME and TEST_LDAP_PASSWORD
  4. Run tests by make check
  5. Run example my make start and try to authorize as test user
  6. Observe traces in Jaeger on http://127.0.0.1:16686/ for app ldap4gin_example

spans.png

MIT License

Copyright (c) 2021 Anatolij Ostroumov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

Package ldap4gin is authenticator for gin framework using ldap server

Index

Constants

View Source
const SessionKeyName = "ldap4gin_user"

SessionKeyName names key used to store user profile in session

Variables

View Source
var (
	ErrUnauthorized             = fmt.Errorf("unauthorized")
	ErrMalformed                = fmt.Errorf("malformed username")
	ErrInvalidCredentials       = fmt.Errorf("invalid credentials")
	ErrNotFound                 = fmt.Errorf("user not found")
	ErrMultipleAccount          = fmt.Errorf("multiple user profiles found")
	ErrReadonlyWrongCredentials = fmt.Errorf("readonly user has wrong credentials")
)
View Source
var DefaultLogDebugFunc = func(ctx context.Context, format string, a ...any) {
	log.Default().Printf("ldap4gin: "+format+"\n", a...)
}

DefaultLogDebugFunc is used for logging by default

Functions

func GetDefaultFields

func GetDefaultFields() []string

GetDefaultFields returns fields we extract from LDAP by default

Types

type Authenticator

type Authenticator struct {

	// Options are runtime options as received from New
	Options *Options
	// LDAPConn is ldap connection being used
	LDAPConn *ldap.Conn
	// LogDebugFunc is function to log debug information
	LogDebugFunc LogDebugFunc
	// contains filtered or unexported fields
}

Authenticator links ldap and gin context together

func New

func New(opts *Options) (a *Authenticator, err error)

New creates new authenticator using options provided

func (*Authenticator) Authorize

func (a *Authenticator) Authorize(c *gin.Context, username, password string) (err error)

Authorize tries to find user in ldap database, check his/her password via `bind` and populate session, if password matches

func (*Authenticator) Close added in v1.1.0

func (a *Authenticator) Close() (err error)

Close closes authenticator connection to ldap

func (*Authenticator) Extract

func (a *Authenticator) Extract(c *gin.Context) (user *User, err error)

Extract extracts users profile from session

func (*Authenticator) Logout

func (a *Authenticator) Logout(c *gin.Context) (err error)

Logout terminates user's session

type Group added in v1.1.0

type Group struct {
	GID         string // gidNumber
	Name        string // cn
	Description string // description
}

Group is member of groups organization unit in ldap

type LogDebugFunc added in v1.2.0

type LogDebugFunc func(ctx context.Context, format string, a ...any)

LogDebugFunc used to define requirements for logging function

type Options

type Options struct {
	// Debug outputs debugging information, better leave it to false
	Debug bool

	// TTL depicts how long user profile is cached in session, when it expires, it is reloaded from ldap
	TTL time.Duration

	//ConnectionString depicts how we dial LDAP server, something like ldap://127.0.0.1:389 or ldaps://ldap.example.org:636
	ConnectionString string
	// TLS is configuration for encryption to use
	TLS *tls.Config
	// StartTLS shows, do we need to execute StartTLS or not
	StartTLS bool

	// ReadonlyDN is distinguished name used for authorization as readonly user,
	// who has access to listing groups of user. For example, "cn=readonly,dc=vodolaz095,dc=ru"
	ReadonlyDN string
	// ReadonlyPasswd is password for readonly user, who has access to listing groups
	ReadonlyPasswd string

	// UserBaseTpl is template to extract user profiles by UID, for example
	// "uid=%s,ou=people,dc=vodolaz095,dc=ru" or
	// "email=%s,ou=people,dc=vodolaz095,dc=ru"
	UserBaseTpl string
	// ExtraFields is array of fields, we also extract from database.
	// NOTICE - if you add too many fields, it can hit session size limits!
	ExtraFields []string

	// ExtractGroups toggles extracting groups of user
	ExtractGroups bool
	// GroupsOU depicts organization unit for groups, usually "ou=groups,dc=vodolaz095,dc=ru"
	GroupsOU string

	// LogDebugFunc is called to log debug events
	LogDebugFunc LogDebugFunc
}

Options depicts parameters used to instantiate Authenticator

type User

type User struct {
	// General
	DN  string // dn: uid=sveta,ou=people,dc=vodolaz095,dc=life
	UID string //uid: sveta

	// Names
	GivenName  string // `givenname` - Svetlana
	CommonName string // `cn` - Svetlana Belaya
	Initials   string // `initials` - SA
	Surname    string // `sn` - Belaya

	// work specific
	Organization     string // o: R&D
	OrganizationUnit string // ou: Laboratory 47
	Title            string // title: developer
	Description      string // description: writes code

	// Internet related
	Website string   // labeleduri: https://vodolaz095.life
	Emails  []string // `mail` user can have few emails

	// Linux specific
	UIDNumber     uint64 // uidnumber 1000
	GIDNumber     uint64 // gidnumber 1000
	HomeDirectory string // homedirectory: /home/sveta
	LoginShell    string // loginshell - /bin/bash

	// groups
	Groups []Group

	// Raw entry extracted from LDAP
	Entry     *ldap.Entry
	ExpiresAt time.Time
}

User depicts profile of authorized user

func (*User) Expired added in v1.1.0

func (u *User) Expired() bool

Expired returns true, if user profile should be reloaded from ldap database

func (*User) HasGroupByGID added in v1.1.0

func (u *User) HasGroupByGID(gid string) (ok bool)

HasGroupByGID checks, if user is a member of group with this GID

func (*User) HasGroupByName added in v1.1.0

func (u *User) HasGroupByName(name string) (ok bool)

HasGroupByName checks, if user is a member of group with this name

func (*User) PrintGroups added in v1.3.0

func (u *User) PrintGroups() string

PrintGroups returns string of user groups in easy to read format

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL