Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过Spring安全性使用java对LDAP用户进行身份验证_Java_Spring_Authentication_Spring Security_Spring Ldap - Fatal编程技术网

通过Spring安全性使用java对LDAP用户进行身份验证

通过Spring安全性使用java对LDAP用户进行身份验证,java,spring,authentication,spring-security,spring-ldap,Java,Spring,Authentication,Spring Security,Spring Ldap,我在Spring安全性和Adam Ldap方面遇到了一些问题。 你可以在没有有用答案的情况下看到我的帖子。 我想用我的验证java代码来设置spring环境。这是我的java代码: @Override public void isAuthenticated(String username, String password) throws LdapException{ if (databaseMatlabClientServices.getByUsersEnabled(username)=

我在Spring安全性和Adam Ldap方面遇到了一些问题。 你可以在没有有用答案的情况下看到我的帖子。 我想用我的验证java代码来设置spring环境。这是我的java代码:

@Override
public void isAuthenticated(String username, String password) throws LdapException{
    if (databaseMatlabClientServices.getByUsersEnabled(username)== null)
        throw new LdapException("User doesn't exist into DART database. Please contact the administrator!");
    String dn="";;
    //First query to retriev DN
    Hashtable<String, Object> ldapEnv = new Hashtable<String, Object>();
    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, env.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
//Without authentication        ldapEnv.put(Context.SECURITY_AUTHENTICATION, "none");
    //With authentication to access to LDAP server
    ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    ldapEnv.put(Context.SECURITY_PRINCIPAL, env.getRequiredProperty(PROPERTY_NAME_LDAP_NAME));
    ldapEnv.put(Context.SECURITY_CREDENTIALS, env.getRequiredProperty(PROPERTY_NAME_LDAP_PASSWORD));
    String[] returnAttribute = {"dn"};
    DirContext ctx = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        ctx = new InitialDirContext(ldapEnv);
        SearchControls controls = new SearchControls();
        controls.setReturningAttributes(returnAttribute);
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// without authentication on local server String filter = "uid=" + username ;
        String filter = "CN=" + username ;
        results = ctx.search(env.getRequiredProperty(PROPERTY_NAME_LDAP_USERSEARCHBASE), filter, controls);
        if (results.hasMore())
            dn = results.nextElement().getNameInNamespace();
        else 
            throw new LdapException("Wrong username. Please retry!");
    } catch (NamingException e) {
        throw new LdapException(e);
    } finally {
        try{
            if (results != null)
                results.close();             
            if (ctx != null) 
                ctx.close();
        }catch(Exception e){
            throw new LdapException(e);
        }
    }

    //Second query to try to access with obtained Dn and given password
    Hashtable<String, Object> authEnv = new Hashtable<String, Object>();
    authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    authEnv.put(Context.PROVIDER_URL, env.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    authEnv.put(Context.SECURITY_PRINCIPAL, dn);
    authEnv.put(Context.SECURITY_CREDENTIALS, password);
    DirContext ctx2 = null;
    try {
        ctx2 = new InitialDirContext(authEnv);
    } catch (AuthenticationException authEx) {
        throw new LdapException("Authentication error. Password was wrong");
    } catch(Exception e){
        throw new LdapException(e);
    }finally {
        try{         
            if (ctx2 != null) 
                ctx2.close();
        }catch(Exception e){
            throw new LdapException(e);
        }
    }
}
@覆盖
public void已验证(字符串用户名、字符串密码)引发LdapException{
if(databaseMatlabClientServices.getByUsersEnabled(username)==null)
抛出新的LdapException(“DART数据库中不存在用户。请与管理员联系!”);
字符串dn=“”;;
//对retriev DN的第一个查询
Hashtable ldapEnv=新的Hashtable();
ldapEnv.put(Context.INITIAL_Context_工厂,“com.sun.jndi.ldap.LdapCtxFactory”);
ldapEnv.put(Context.PROVIDER\u URL,env.getRequiredProperty(PROPERTY\u NAME\u LDAP\u URL));
//无身份验证ldapEnv.put(Context.SECURITY_身份验证,“无”);
//通过身份验证访问LDAP服务器
ldapEnv.put(Context.SECURITY_身份验证,“simple”);
ldapEnv.put(Context.SECURITY\u PRINCIPAL,env.getRequiredProperty(PROPERTY\u NAME\u LDAP\u NAME));
ldapEnv.put(Context.SECURITY\u凭证,env.getRequiredProperty(属性名称LDAP\u密码));
字符串[]returnAttribute={“dn”};
DirContext ctx=null;
NamingEnumeration结果=空;
试一试{
ctx=新的InitialDirContext(ldapEnv);
SearchControls=新的SearchControls();
控件。设置ReturningAttribute(returnAttribute);
控件.setSearchScope(SearchControls.SUBTREE_范围);
//在本地服务器上没有身份验证字符串filter=“uid=”+用户名;
String filter=“CN=”+用户名;
results=ctx.search(env.getRequiredProperty(PROPERTY\u NAME\u LDAP\u USERSEARCHBASE)、过滤器、控件);
if(results.hasMore())
dn=results.nextElement().getNameInNamespace();
其他的
抛出新的LdapException(“错误的用户名。请重试!”);
}捕获(NamingE例外){
抛出新的LdapException(e);
}最后{
试一试{
如果(结果!=null)
结果:关闭();
如果(ctx!=null)
ctx.close();
}捕获(例外e){
抛出新的LdapException(e);
}
}
//尝试使用获得的Dn和给定密码访问的第二个查询
Hashtable authEnv=新的Hashtable();
authEnv.put(Context.INITIAL_Context_工厂,“com.sun.jndi.ldap.LdapCtxFactory”);
authEnv.put(Context.PROVIDER\u URL,env.getRequiredProperty(PROPERTY\u NAME\u LDAP\u URL));
authEnv.put(Context.SECURITY_身份验证,“simple”);
authEnv.put(Context.SECURITY\u主体,dn);
authEnv.put(Context.SECURITY\u凭证、密码);
DirContext ctx2=null;
试一试{
ctx2=新的InitialDirContext(authEnv);
}捕获(AuthenticationException authEx){
抛出新的LdapException(“身份验证错误。密码错误”);
}捕获(例外e){
抛出新的LdapException(e);
}最后{
试试{
如果(ctx2!=null)
ctx2.close();
}捕获(例外e){
抛出新的LdapException(e);
}
}
}
此代码识别Ldap系统上是否存在用户和密码。 春天我有

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldaps://vdap.floal:636/");
    contextSource.setBase("DC=fg,DC=local");
    contextSource.setReferral("follow"); 
    contextSource.setUserDn("CN=A00XXX32,CN=Administration,CN=fdam,DC=fg,DC=local");
    contextSource.setPassword(password);
    contextSource.afterPropertiesSet();
    LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>      ldapAuthenticationProviderConfigurer = auth.ldapAuthentication();
    ldapAuthenticationProviderConfigurer
    .contextSource(contextSource)
    .userSearchBase("CN=fdam")
    .userSearchFilter(env.getRequiredProperty("(CN={0})"))
    .ldapAuthoritiesPopulator(myAuthPopulator);     
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)引发异常{
LdapContextSource contextSource=新的LdapContextSource();
contextSource.setUrl(“ldaps://vdap.floal:636/");
setBase(“DC=fg,DC=local”);
contextSource.setReferral(“follow”);
setUserDn(“CN=A00XXX32,CN=Administration,CN=fdam,DC=fg,DC=local”);
contextSource.setPassword(密码);
contextSource.AfterPropertieSet();
LdapAuthenticationProviderConfigurer LdapAuthenticationProviderConfigurer=auth.ldapAuthentication();
ldapAuthenticationProviderConfigurer
.contextSource(contextSource)
.userSearchBase(“CN=fdam”)
.userSearchFilter(env.getRequiredProperty(“(CN={0})”)
.ldaAuthoritiesPopulator(myAuthPopulator);
}
和我的授权人员从数据库中提供角色信息

@Service("myAuthPopulator")
public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {

    @Autowired
    private UserServices userServices;
    static final Logger LOG = LoggerFactory.getLogger(MyAuthoritiesPopulator.class);

    @Transactional(readOnly=true)
    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        try{
            com.domain.User user = userServices.getByUsersEnabled(username);
            if (user==null){
                LOG.error("Threw exception in MyAuthoritiesPopulator::getGrantedAuthorities : User doesn't exist into DART database" );
            }
            else{
                //Use this if a user can have different roles
//              for(Role role : user.getRole()) {
//                  authorities.add(new SimpleGrantedAuthority(role.getRole()));
//              }
                authorities.add(new SimpleGrantedAuthority(user.getRole().getRole()));
                return authorities;
            }
        }catch(Exception e){
            LOG.error("Threw exception in MyAuthoritiesPopulator::getGrantedAuthorities : " + ErrorExceptionBuilder.buildErrorResponse(e)); }
        return authorities;
    }
}
@服务(“myAuthPopulator”)
公共类MyAuthoritiesPopulator实现了LdapAuthoritiesPopulator{
@自动连线
私人用户服务;
静态最终记录器日志=LoggerFactory.getLogger(MyAuthoritiesPopulator.class);
@事务(只读=真)
@凌驾

公共集合没有解决方案?我是否可以通过xml而不是批注只设置Spring Ldap?没有解决方案?我是否可以通过xml而不是批注只设置Spring Ldap?