Spring + LDAP

来源:互联网 发布:php调取数据库 编辑:程序博客网 时间:2024/05/22 23:49

这两天做了一个日报系统,是用LDAP实现登录的,现把一些重要的地方记录如下:

1.Spring xml配置:

<bean id="ldapContextSource" class="org.springframework.ldap.core.support.LdapContextSource"><property name="referral" value="follow"></property><property name="url" value="ldap://127.0.0.1:389" /><!--  --><property name="base" value="ou=user,dc=cq,dc=cst,dc=com" /><property name="userDn" value="cn=Manager,dc=cst,dc=com" /><property name="password" value="secret" /><property name="baseEnvironmentProperties"><map><entry key="java.naming.security.authentication" value="simple" /></map></property></bean><bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate"><property name="contextSource" ref="ldapContextSource" /></bean>

注意:base:"ou=user,dc=cq,dc=cst,dc=com"的顺序,它是从右到左的,我们操作的是user这个节点下的数据;



2.LDAP用户的登录校验:

 /**  * LDAP的登录  * @param userId  * @param password  * @return  */    public boolean authUser(String userId, String password) {       boolean flag  =  false;    try {flag =ldapTemplate.authenticate("", "(uid="+userId+")",password);} catch (Exception e) {}    return flag;        }  

3.用户信息查询

    public User find(String username) {                String rdn = ("uid="+username);               return (User)ldapTemplate.lookup(rdn, new UserAttributesMapper());            }            /**     * 根据用户名查询用户信息     * @author Administrator     *     */    private class UserAttributesMapper implements AttributesMapper {                public Object mapFromAttributes(Attributes attrs) throws NamingException {          User user = new User();          if(attrs.get("displayName")!=null){        Object displayName = attrs.get("displayName").get();        user.setDisplayName(displayName.toString());        }            if(attrs.get("uid")!=null){            Object uid = attrs.get("uid").get();        user.setUsername(uid.toString());            }            if(attrs.get("title")!=null){            Object title = attrs.get("title").get();        user.setTitle(title.toString());            }            return user;          }        } 


0 0
原创粉丝点击