0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Goのldapモジュールで認証をLDAP認証をかける

Posted at

認証したいユーザー

  • cn=yuta

ldapモジュールをインストール

go get github.com/go-ldap/ldap

サンプルコード


package main

import (
	"fmt"
	"github.com/go-ldap/ldap/v3"
	"log"
)

var (
	ldapServer = "ldap://localhost:389"
	baseDN     = "dc=vamdemic,dc=black"
	username = "yuta"
	password = "password"
	bindusername = "cn=admin,dc=vamdemic,dc=black"
	bindpassword = "password"

)

// This example shows how a typical application can verify a login attempt
func Example_userAuthentication() {
	l, err := ldap.DialURL(ldapServer)
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	// First bind with a read only user
	err = l.Bind(bindusername, bindpassword)
	if err != nil {
		log.Fatal(err)
	}

	// Search for the given username
	searchRequest := ldap.NewSearchRequest(
		baseDN,
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=organizationalPerson)(cn=%s))", 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)
	}
}

func main() {
	Example_userAuthentication()
}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?