ldap4gin

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: May 30, 2022 License: MIT Imports: 10 Imported by: 0

README

ldap4gin

Authenticator for gin framework using ldap server

Go Report Card GoDoc

Advertisement

You can hire the author of this package by Upwork - https://www.upwork.com/freelancers/~0120ba573d09c66c51

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


package main

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

   "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",
      UserBaseTpl:      "uid=%s,ou=people,dc=vodolaz095,dc=life",
      TLS:              &tls.Config{}, // nearly sane default values
      StartTLS:         false,
      ExtraFields:      []string{"l"}, // get location too
   })
   if err != nil {
      log.Fatalf("%s : while initializing ldap4gin authenticator", err)
   }
   log.Println("LDAP server dialed!")

   // 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()
      //  extracting user's profile from context
      user, err := authenticator.Extract(c)
      if err != nil {
         if err.Error() == "unauthorized" { // render login page
            session.AddFlash("Authorization failed")
            session.Save()
            c.HTML(http.StatusUnauthorized, "unauthorized.html", gin.H{
               "flashes": flashes,
            })
            return
         }
         if err.Error() == "malformed username" {
            session.AddFlash("Malformed username")
            session.Save()
            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)
      }
      session.Save()
      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)
      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))
      } else {
         log.Printf("User %s authorized from %s!", username, c.ClientIP())
         session.AddFlash(fmt.Sprintf("Welcome, %s!", username))
      }
      session.Save()
      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 authorize.go 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

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

This section is empty.

Functions

func GetDefaultFields

func GetDefaultFields() []string

GetDefaultFields returns fields we extract from LDAP by default

Types

type Authenticator

type Authenticator struct {

	// LDAPConn is ldap connection being used
	LDAPConn *ldap.Conn
	// 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) 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 Options

type Options struct {
	// Debug outputs debugging information, better leave it to false
	Debug bool
	//ConnectionString depicts how we dial LDAP server, something like ldap://127.0.0.1:389 or ldaps://ldap.example.org:636
	ConnectionString string
	// UserBaseTpl is template to extract user profiles by UID, for example  "uid=%s,ou=people,dc=example,dc=org",
	UserBaseTpl string
	// TLS is configuration for encryption to use
	TLS *tls.Config
	// StartTLS shows, do we need to execute StartTLS or not
	StartTLS bool
	// 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
}

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 // 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

	// Raw entry extracted from LDAP
	Entry *ldap.Entry
}

User depicts profile of authorized user

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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