导语:通过golang对ldap用户进行校验。以便后期使用。
package main
import (
"fmt"
"log"
"github.com/go-ldap/ldap/v3"
)
func main() {
// The username and password we want to check
username := "user"
password := "password"
bindusername := "cn=admin,dc=example,dc=com"
// bindusername := "admin"
bindpassword := "passwd123456"
// l, err := DialURL("ldap://ldap.example.com:389")
l, err := ldap.DialURL("ldap://ldap.example.com:389")
if err != nil {
log.Fatal(err)
}
defer l.Close()
fmt.Println("0000")
// Reconnect with TLS
// err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
// if err != nil {
// log.Fatal(err)
// }
fmt.Println("1111")
// First bind with a read only user
err = l.Bind(bindusername, bindpassword)
if err != nil {
log.Fatal(err)
}
fmt.Println("2222")
// Search for the given username
searchRequest := ldap.NewSearchRequest(
"dc=deepwise,dc=com",
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=organizationalPerson)(uid=%s))", ldap.EscapeFilter(username)),
[]string{"dn"},
nil,
)
sr, err := l.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
if len(sr.Entries) != 1 {
log.Fatal("User does not exist or too many entries returned")
}
userdn := sr.Entries[0].DN
// Bind as the user to verify their password
err = l.Bind(userdn, password)
if err != nil {
log.Fatal(err)
}
// Rebind as the read only user for any further queries
err = l.Bind(bindusername, bindpassword)
if err != nil {
log.Fatal(err)
}
}
报错 LDAP Result Code 34 “Invalid DN Syntax”: invalid DN是binduser用了admin
需要用bindusername := "cn=admin,dc=example,dc=com"
使用正确/错误 密码进行校验的结果如下。
参考
https://pkg.go.dev/github.com/go-ldap/ldap/v3