⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ldapsavingutility.java

📁 一个完整的XACML工程,学习XACML技术的好例子!
💻 JAVA
字号:
/*
* Copyright (c) 2000-2005, University of Salford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this 
* list of conditions and the following disclaimer.
* 
* Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation 
* and/or other materials provided with the distribution. 
*
* Neither the name of the University of Salford nor the names of its 
* contributors may be used to endorse or promote products derived from this 
* software without specific prior written permission. 
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
* POSSIBILITY OF SUCH DAMAGE.
*/

package issrg.pa.extensions;

import javax.naming.*;
import javax.naming.directory.*;
import javax.swing.*;
import issrg.pa.ACCreationException;

/**
 * This is the LDAP saving utility.
 *
 * <p>This utility saves the given Attribute Certificate to an LDAP Directory,
 * of which the URL a user can enter in a dialog. The DN to save to is obtained
 * from the AC to save; the DN to load from the user should type in.
 *
 * <p>Simple authentication to the LDAP server is supported.
 *
 * <p>The utility was tested on LDAP v3 only.
 *
 * @author A Otenko
 * @version 1.0
 */

public class LDAPSavingUtility extends issrg.pa.SavingUtility{
  /**
   * The variable, containing the name of the configuration variable, representing
   * the LDAP server URI. At the moment it is "LDAPSavingUtility.ProviderURI".
   */
  final public static String LDAP_SAVING_UTILITY_LDAP_PROVIDER = "LDAPSavingUtility.ProviderURI";

  /**
   * The variable, containing the name of the configuration variable, representing
   * the default login for accessing LDAP server. (Usually such authentication is
   * set for writing only.) The user may change this value at run time. At the
   * moment it is "LDAPSavingUtility.Login". Note, that only simple authentication
   * is suported at the moment.
   */
  final public static String LDAP_SAVING_UTILITY_LOGIN = "LDAPSavingUtility.Login";

  /**
   * The variable, containing the name of the configuration variable, representing
   * the default name of the attribute the LDAPSavingUtility will
   * retrieve and store. At the moment it is "LDAPSavingUtility.ACType".
   */
  final public static String LDAP_SAVING_UTILITY_AC_TYPE = "LDAPSavingUtility.ACType";

  /**
   * The variable, containing the name of the attribute the LDAPSavingUtility will
   * retrieve and store. At the moment it is "2.5.4.58;binary".
   * the OID of the attribute is 2.5.4.58.
   */
  final public static String ATTRIBUTE_CERTIFICATE_ATTRIBUTE_NAME = "2.5.4.58;binary";//"x509AttributeCertificate;binary"; //"2.5.4.58";

  final private JTextField URL = new JTextField();
  final private JTextField DN = new JTextField();
  final private JTextField Login = new JTextField();
  final private JPasswordField Password = new JPasswordField();
  final private JCheckBox Anonymous = new JCheckBox("Anonymous", false);
  final private javax.swing.JRadioButton AddValueButton = new javax.swing.JRadioButton("Add value", true);
  final private javax.swing.JRadioButton ReplaceValueButton = new javax.swing.JRadioButton("Replace value", false);

  private String lastURL = null;
  private String lastDN = null;
  private String lastLogin = null;
  private String acType=ATTRIBUTE_CERTIFICATE_ATTRIBUTE_NAME;

  public LDAPSavingUtility(){
    super();

    java.awt.event.ActionListener al = new java.awt.event.ActionListener(){
        public void actionPerformed(java.awt.event.ActionEvent ae){
          AddValueButton.setSelected(false);
          ReplaceValueButton.setSelected(false);
          ((javax.swing.JRadioButton)ae.getSource()).setSelected(true);
        }
      };
    AddValueButton.addActionListener(al);
    ReplaceValueButton.addActionListener(al);
  }

  public void save(java.awt.Frame frame, byte [] ac, java.util.Map env) throws ACCreationException{
    String dn="";
    JDialog splash=null;
    try{
      issrg.ac.Holder h = new issrg.ac.AttributeCertificate(iaik.asn1.DerCoder.decode(ac)).getACInfo().getHolder();
      dn = issrg.ac.Util.generalNamesToString(h.getEntityName());
      if (dn.intern()==""){
        dn = issrg.ac.Util.issuerSerialToDN(
                issrg.ac.Util.generalNamesToString(h.getBaseCertificateID().getIssuer()),
                                              h.getBaseCertificateID().getSerial()
                                             );
      }

      initDefaults(env);

      if (!showDialog(frame, dn, lastURL, lastLogin, false)) return;
      dn = DN.getText();
      splash=showSplash(frame);

      DirContext root = connectTo(URL.getText(), Login.getText(), new String(Password.getPassword()), Anonymous.isSelected());
      root.modifyAttributes(dn, AddValueButton.isSelected()?DirContext.ADD_ATTRIBUTE:DirContext.REPLACE_ATTRIBUTE,
                                new BasicAttributes(
                                  acType,
                                  ac
                                )
                          );

      lastDN=DN.getText();
      lastURL=URL.getText();
      lastLogin=Login.getText();
    }catch (iaik.asn1.CodingException ce){
      throw new ACCreationException("Prohibited action: cannot save as this is not an AC\n"+ce.getMessage(), ce);
    }catch (NamingException ne){
      throw new ACCreationException("Cannot access "+dn+" entry", ne);
    }catch (NoClassDefFoundError ncdfe){
      throw new ACCreationException("Cannot load the required class.\nAre there any classes missing from the classpath?\nClass name: ["+ncdfe.getMessage()+"]", ncdfe);
    }catch (Exception e){
      throw new ACCreationException("Internal error", e);
    }finally{
      if (splash!=null){
        splash.dispose();
      }
    }
  }

  public issrg.ac.AttributeCertificate load(java.awt.Frame frame, java.util.Map env) throws ACCreationException{
    JDialog splash = null;

    String dn = "";
    try{
      initDefaults(env);
      if (!showDialog(frame, "", lastURL, lastLogin, true)) return null;

      splash = showSplash(frame);
      dn = DN.getText();

      java.util.Hashtable e = new java.util.Hashtable();

      DirContext root = connectTo(URL.getText(), Login.getText(), new String(Password.getPassword()), Anonymous.isSelected());
      String [] attrIds = new String[]{acType};
      Attributes atts = root.getAttributes(dn, attrIds);
      Attribute att = null;//atts.get(attrIds[0]);
      for (NamingEnumeration ne = atts.getAll(); ne.hasMoreElements();){  // it should not happen to return more than one attribute; but if it does, then only the last attribute in the list will be remembered
        att = (Attribute)ne.nextElement();
      }
      if (att==null){
        return null;  // no X509 ACs has been found there
      }

      //****** this was debugging
      /*System.out.println("Attributes retrieved: "+atts.size());
      *for (java.util.Enumeration e1 = atts.getAll(); e1.hasMoreElements();){
      *  Attribute a = (Attribute)e1.nextElement();
      *  System.out.println(a.getID()+"="+a.get()+", which is of type "+a.get().getClass().getName()+", and of size "+a.size());
      *  for (java.util.Enumeration e2 = a.getAll(); e2.hasMoreElements(); ){
      *    Object o = e2.nextElement();
      *    System.out.println(o.getClass().getName()+": "+o.toString());
      *  }
      *}
      */

      //char [] c = att.size()!=0?((String)att.get()).toCharArray(): new char[0];
      //byte [] ac = new byte[c.length];

      //for (int i = 0; i<c.length; i++) ac[i]=(byte)((c[i]) & 0xff);

      //ac = (byte [])iaik.asn1.DerCoder.decode(ac).getValue(); // it must be an OCTET_STRING, when decoded
      byte [] ac = (att.size()!=0)?((byte [])att.get()): new byte[0];   // if no ACs are there, assume an empty array; we'll get CodingException

      //try{new java.io.FileOutputStream("ldap_ac").write(ac);}catch(Exception ex){}

      lastDN=DN.getText();
      lastURL=URL.getText();
      lastLogin=Login.getText();
      return issrg.ac.AttributeCertificate.guessEncoding(ac);
    }catch (iaik.asn1.CodingException ce){
      throw new ACCreationException("Error retrieving an AC: not an AC", ce);
    }catch (NamingException ne){
      throw new ACCreationException("Cannot access "+dn+" entry\n"+ne.getMessage(), ne);
    }catch (NoClassDefFoundError ncdfe){
      throw new ACCreationException("Cannot load the required class.\nAre there any classes missing from the classpath?\nClass name: ["+ncdfe.getMessage()+"]", ncdfe);
    }finally{
      if (splash!=null){
        splash.setVisible(false);
      }
    }
  }

  /**
   * This method displays the dialog box with URI/DN/Login/Password fields and
   * returns true, if clicked [OK]; false, otherwise. URL, DN, Login and Password
   * are filled in, and Anonymous is ticked.
   */
  private boolean showDialog(java.awt.Frame owner, String dn, String url, String login, boolean openDialog){
    final int CANCEL_OPTION = 0;
    final int OK_OPTION = 1;
    final JDialog d = new JDialog(owner, true);
    final int [] modal_result = new int [1];
    int yshift = openDialog?0:25;

    modal_result[0]=CANCEL_OPTION;

    DN.setText(dn);
    DN.setEditable(openDialog);
    URL.setText(url==null?"":url);
    Login.setText(login==null?"":login);
    Password.setText(""); // always clear the password field

    d.setTitle("Enter LDAP Directory parameters:");
    d.setResizable(false);
    d.setSize(360, 140+yshift);

    java.awt.Dimension g = java.awt.Toolkit.getDefaultToolkit().getScreenSize();

    d.setLocation((g.width-d.getWidth()) / 2,
                  (g.height-d.getHeight()) / 2);

    JPanel p = (JPanel)d.getContentPane();
    p.setLayout(null);

    // *** Row 1
    JLabel l = new JLabel("LDAP URL:");
    l.setSize(60, 20);
    l.setLocation(4,2);
    p.add(l, null);

    URL.setSize(180, 20);
    URL.setLocation(72, 2);
    p.add(URL, null);

    JButton b = new JButton("Cancel");
    b.setSize(90,20);
    b.setLocation(256, 2);
    b.addActionListener(new java.awt.event.ActionListener(){
        public void actionPerformed(java.awt.event.ActionEvent a){
          d.setVisible(false);
        }
      });

    p.add(b);


    // *** Row 2
    l = new JLabel("DN:");
    l.setSize(60, 20);
    l.setLocation(4,30);
    p.add(l, null);

    DN.setSize(180, 20);
    DN.setLocation(72, 30);
    p.add(DN, null);

    b = new JButton("OK");
    b.setSize(90,20);
    b.setLocation(256, 30);
    b.addActionListener(new java.awt.event.ActionListener(){
        public void actionPerformed(java.awt.event.ActionEvent a){ // close the window
          modal_result[0]=OK_OPTION;
          d.setVisible(false);
        }
      });

    p.add(b);

    javax.swing.JSeparator sep = new javax.swing.JSeparator(javax.swing.JSeparator.HORIZONTAL);
    sep.setBounds(2, 55, 346, 2);
    p.add(sep);

    if (!openDialog){
      AddValueButton.setBounds(2, 60, 170, 20);
      p.add(AddValueButton);

      ReplaceValueButton.setBounds(180, 60, 170, 20);
      p.add(ReplaceValueButton);

      sep = new javax.swing.JSeparator(javax.swing.JSeparator.HORIZONTAL);
      sep.setBounds(2, 80, 346, 2);
      p.add(sep);
    }

    // *** Row 3
    l=new JLabel("Login:");
    l.setBounds(2, 60+yshift, 70, 20);
    p.add(l);

    Login.setBounds(72, 60+yshift, 180, 20);
    p.add(this.Login);

    Anonymous.setBounds(256, 60+yshift, 90, 20);
    p.add(Anonymous);


    // *** Row 4
    l=new JLabel("Password:");
    l.setBounds(2, 90+yshift, 70, 20);
    p.add(l);

    Password.setBounds(72, 90+yshift, 180, 20);
    p.add(this.Password);

    d.show();

    return modal_result[0]==OK_OPTION;    // if URL field is set to "" ([Cancel] or [x] or did not input) do not even attempt to continue
  }

  private JDialog showSplash(java.awt.Frame owner){
    return issrg.utils.Util.showSplash(owner, "Please, wait...", "Connecting to the LDAP server...");
  }

  /**
   * Just a wrapper for establishing connection to the LDAP DIT.
   */
  private DirContext connectTo(String URL, String login, String password, boolean anonymous) throws NamingException{
      java.util.Hashtable e = new java.util.Hashtable();
      e.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      e.put(Context.PROVIDER_URL, URL);
      e.put("java.naming.ldap.version", "3");
      e.put("java.naming.ldap.attributes.binary", acType); // otherwise it may sometimes retrieve it as a String :-(, stupid thing

      if (login!=null && password!=null && !anonymous){
        e.put(Context.SECURITY_AUTHENTICATION, "simple");
        e.put(Context.SECURITY_PRINCIPAL, login);
        e.put(Context.SECURITY_CREDENTIALS, password);
      }

      return new InitialDirContext(e);
  }

  /**
   * Reads in the environment settings: cfg variables, and sets them if needed.
   */
  private void initDefaults(java.util.Map env){
      if (env==null) return;

      if (lastURL == null) lastURL = (String)env.get(this.LDAP_SAVING_UTILITY_LDAP_PROVIDER);
      if (lastLogin==null) lastLogin = (String)env.get(this.LDAP_SAVING_UTILITY_LOGIN);

      String s=(String)env.get(LDAP_SAVING_UTILITY_AC_TYPE);
      if (s!=null) acType=s;
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -