docker安裝gitlab集成OpenLDAP

回顧一下OpenLDAP,請參見上一篇文章 docker安裝部署OpenLdap

直接進入主題吧,上一篇已經安裝好了OpenLDAP,那麼我們就要使用起來,具體怎麼用了,這邊文章我們來學習下使用gitlab來集成它。

1.創建gitlab-ce

我們使用gitlab鏡像爲 gitlab/gitlab-ce

提前創建幾個目錄來供gitlab使用。

           /usr/local/gitlab/data

/usr/local/gitlab/logs

/usr/local/gitlab/config  #這個目錄掛載出來是爲了方便修改gitlab.rb配置文件

           然後再創建容器

docker run -d    \
--hostname 10.0.43.206    \
--name gitlab-ce     \
--restart always    \
--publish 30022:22 \
--publish 30080:80 \
--publish 30443:443     \
--volume /usr/local/gitlab/data:/var/opt/gitlab     \
--volume /usr/local/gitlab/logs:/var/log/gitlab     \
--volume /usr/local/gitlab/config:/etc/gitlab     \
gitlab/gitlab-ce

容器啓動成功後,可以在/usr/local/gitlab/config目錄找到gitlab.rb文件

編輯,添加如下命令,注意格式哦~~

vim gitlab.rb

 gitlab_rails['ldap_enabled'] = true
 gitlab_rails['ldap_servers'] = YAML.load <<-'EOS'
   main: # 'main' is the GitLab 'provider ID' of this LDAP server
     label: 'LDAP'
     host: '10.0.43.206'
     port: 389
     uid: 'cn'
     method: 'plain' # "tls" or "ssl" or "plain"
     bind_dn: 'cn=admin,dc=youedata,dc=com'
     password: 'youedata2018_'
     allow_username_or_email_login: false
     base: 'ou=People,dc=youedata,dc=com'
     attributes:
       username: ['uid']
       email:    ['mail']
       first_name: 'sn'
 
 EOS

添加完了之後,一定要看下前面結束標誌是否變色了,我是用vim,會變色,其他vi是不會變色的。

然後開始刷新配置。在容器中執行。 gitlab-ctl reconfigure

沒有報錯的話就集成完了。打開gitlab的首頁。有LDAP登陸方式了。

注意:這裏如果打開首頁報錯502的話, 就多刷幾次,可能是加載還不完全。耐心等待一下。

這時候尷尬的事情發生了,沒有賬號登陸,所以我們得去創建一個賬號來登陸下。

可以用上一篇文章的phpldapadmin工具,也可以用LDAP Admin

我這裏使用Java代碼來創建賬號,然後登陸。

調用代碼前,得先去創建一個OU(Organizational Unit),使用LDAP Admin工具,先連接到ldap

創建OU

然後就可以使用代碼創建了。

 

貼下代碼。比較粗糙,。。。。我自己都看不上。。。。將就看吧。

package com.example.ldap;
 
import java.util.Hashtable;
import java.util.Random;

import javax.naming.AuthenticationException;  
import javax.naming.Context;  
import javax.naming.NamingEnumeration;  
import javax.naming.NamingException;  
import javax.naming.directory.BasicAttribute;  
import javax.naming.directory.BasicAttributes;  
import javax.naming.directory.SearchControls;  
import javax.naming.directory.SearchResult;  
import javax.naming.ldap.Control;  
import javax.naming.ldap.InitialLdapContext;  
import javax.naming.ldap.LdapContext;

/**
 * @author monkey
 * @date 2019-06-28
 * @desc ldap demo
 */
public class LDAPAuthentication {  

    private final String URL = "ldap://10.0.43.206:389/";
    private final String BASEDN = "ou=people,dc=youedata,dc=com";  // 根據自己情況進行修改
    private final String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
    private LdapContext ctx = null;  
    private final Control[] connCtls = null;  
    
    private void LDAP_connect() {  
        Hashtable<String, String> env = new Hashtable<String, String>();  
        env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);  
        env.put(Context.PROVIDER_URL, URL + BASEDN);  
        env.put(Context.SECURITY_AUTHENTICATION, "simple");  
            
        String root = "cn=admin,dc=youedata,dc=com";  //根據自己情況修改
        env.put(Context.SECURITY_PRINCIPAL, root);   // 管理員  
        env.put(Context.SECURITY_CREDENTIALS, "youedata520");  // 管理員密碼
           
        try {  
            ctx = new InitialLdapContext(env, connCtls);  
            System.out.println( "LDAP_connect連接成功" );
               
        } catch (javax.naming.AuthenticationException e) {  
            System.out.println("連接失敗:");  
            e.printStackTrace();  
        } catch (Exception e) {  
            System.out.println("連接出錯:");  
            e.printStackTrace();  
        }  
           
    }  
  private void closeContext(){  
    if (ctx != null) {  
    try {  
        ctx.close();  
    }  
    catch (NamingException e) {  
        e.printStackTrace();  
    }  
  
}  
  }  
    private String getUserDN(String uid) {  
        String userDN = "";  
        LDAP_connect();  
        try {  
            SearchControls constraints = new SearchControls();  
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);  
              
            NamingEnumeration<SearchResult> en = ctx.search("", "uid=" + uid, constraints);  
              
            if (en == null || !en.hasMoreElements()) {  
                System.out.println("未找到該用戶");  
            }  
            // maybe more than one element  
            while (en != null && en.hasMoreElements()) {  
                Object obj = en.nextElement();  
                if (obj instanceof SearchResult) {  
                    SearchResult si = (SearchResult) obj;  
                    userDN += si.getName();  
                    userDN += "," + BASEDN;  
                } else {  
                    System.out.println(obj);  
                }  
            }  
        } catch (Exception e) {  
            System.out.println("查找用戶時產生異常。");  
            e.printStackTrace();  
        }  
    
        return userDN;  
    }  
    
    public boolean authenricate(String UID, String password) {  
        boolean valide = false;  
        String userDN = getUserDN(UID);  
    
        try {  
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);  
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);  
            ctx.reconnect(connCtls);  
            System.out.println(userDN + " 驗證通過");  
            valide = true;  
        } catch (AuthenticationException e) {  
            System.out.println(userDN + " 驗證失敗");  
            System.out.println(e.toString());  
            valide = false;  
        } catch (NamingException e) {  
            System.out.println(userDN + " 驗證失敗");  
            valide = false;  
        }  
        closeContext();  
        return valide;  
    }  
    private  boolean addUser(String usr, String pwd) {  
        
        try {  
            LDAP_connect();  
            BasicAttributes attrsbu = new BasicAttributes();  
            BasicAttribute objclassSet = new BasicAttribute("objectclass");
            //可以和數據庫關聯,做一個自增,比如mysql存起來
            String str = new Random().nextInt(10000) + "";
            objclassSet.add("inetOrgPerson");  
            objclassSet.add("top");
            objclassSet.add("posixAccount");
            attrsbu.put(objclassSet);
            attrsbu.put("sn", usr);  
            attrsbu.put("cn", usr);  
            attrsbu.put("uid", usr);  
            //郵箱不能重複,不然賬號無法登陸
            attrsbu.put("mail", "[email protected]");
            attrsbu.put("gidNumber", str);
            attrsbu.put("uidNumber", str);
            attrsbu.put("homeDirectory", "/home/account");

            attrsbu.put("userPassword", pwd);
            ctx.createSubcontext("uid="+ usr , attrsbu);

            System.out.println("======================>" + usr + "添加成功");
            return true;  
        } catch (NamingException ex) {  
           ex.printStackTrace();  
        }  
        closeContext();  
        return false;  
    }   
    public static void main(String[] args) {  
        LDAPAuthentication ldap = new LDAPAuthentication();  
          
        ldap.LDAP_connect();  
   
        ldap.addUser("qq1111","123456");
        if(ldap.authenricate("qq1111", "123456") == true){

            System.out.println( "該用戶認證成功" );

        }

    }  
}  

創建賬號登陸之後就成功啦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章