Skip to content

Instantly share code, notes, and snippets.

@pablospizzamiglio
Last active July 18, 2020 12:43
Show Gist options
  • Save pablospizzamiglio/e39069ac0e8aad53709b6e32751de4cb to your computer and use it in GitHub Desktop.
Save pablospizzamiglio/e39069ac0e8aad53709b6e32751de4cb to your computer and use it in GitHub Desktop.
Golang "gopkg.in/ldap.v3" usage with on premises Active Directory
package main
import (
"crypto/tls"
"fmt"
"log"
"gopkg.in/ldap.v3"
)
func main() {
username := "username@example.com"
password := "password"
ldapServer := "ldap.example.com"
// Try to connect to LDAP server
conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, 389))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// Reconnect with TLS
err = conn.StartTLS(&tls.Config{InsecureSkipVerify: true})
if err != nil {
log.Fatal(err)
}
// Bind as the user to verify their password
// If this operation doesn't trigger an error then it's considered as a successful login
err = conn.Bind(username, password)
if err != nil {
log.Fatal(err)
}
// Search for the given username
// Query for other attributes related to the user
searchRequest := ldap.NewSearchRequest(
// The base domain name to search
"dc=example,dc=com",
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
// The filter to apply
// See https://ldapwiki.com/wiki/LDAP%20Query%20Examples
fmt.Sprintf("(&(objectClass=organizationalPerson)(userPrincipalName=%s))", username),
// List of attributes to retrieve
[]string{"cn", "c", "displayName", "userPrincipalName"},
nil,
)
searchResult, err := conn.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
fmt.Println(searchResult)
if len(searchResult.Entries) != 1 {
log.Fatal("User does not exist or too many entries returned")
}
// Prints the result with 2 spaces for indentation
searchResult.PrettyPrint(2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment