简体   繁体   中英

WebSecurityConfig Java equivalent for spring LDAP authentication done with spring-security.xml

I implemented the LDAP authentication and authorization using Spring Security in my project. I configured the spring-security.xml and got it running. I am trying to do the same using Java (WebSecurityConfig.java). Can someone guide me on how to do this?

Here is my spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/security 
            http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <!-- This is where we configure Spring-Security  -->
    <security:http auto-config="true" use-expressions="true"  >

        <security:intercept-url pattern="/main/common" access="hasRole('role.xyz.WebAdmin')"/>
        <security:intercept-url pattern="/admincare" access="hasRole('role.xyz.WebAdmin')"/>

        <security:form-login
                login-page="/auth/login" 
                authentication-failure-url="/auth/login?error=true" 
                default-target-url="/main/common"/>

        <security:logout 
                invalidate-session="true" 
                logout-success-url="/auth/login" 
                logout-url="/auth/logout"/>

    </security:http>


            <security:authentication-manager>

        <security:authentication-provider ref="ldapAuthProvider" />
    </security:authentication-manager>

    <bean id="ldapAuthProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
        <constructor-arg name="authenticator">
            <bean class="org.springframework.security.ldap.authentication.BindAuthenticator">
                <constructor-arg ref="ldapContext" />
                <property name="userSearch">
                    <bean class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
                        <constructor-arg name="searchBase" value="" />
                        <constructor-arg name="searchFilter" value="(&amp;(uid={0})(objectclass=person)(ums-account-state=OK))" />
                        <constructor-arg name="contextSource" ref="ldapContext" />
                    </bean>
                </property>
            </bean>
        </constructor-arg>
        <constructor-arg>
            <bean class="com.gemalto.mobileid.service.UmsLdapAuthoritiesPopulator">
                <constructor-arg ref="ldapContext"/>
            </bean>
        </constructor-arg>
    </bean>

    <security:ldap-server id="ldapContext" url="ldap://aaa:54389/dc=xxx.com" manager-dn="bbb" manager-password="ccc" /> 
</beans>

Now, if I want to do same in the JAVA style (in WebSecurityConfig.java) and get rid of the XML, how do I do? I am not so familiar with the APIs provided for this. I started it this way:

    public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("", "ldap://aaa:54389/dc=xxx.com");
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        provider.setUseAuthenticationRequestCredentials(true);
        return provider;
    }

    @Bean
    public LoggerListener loggerListener() {
        return new LoggerListener();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Configuration for Redirects, Login-Page and stuff

        http
        .authorizeRequests()
            .antMatchers("/admincare").authenticated()
            .and()
        .formLogin();
            //.loginPage("/auth/login")
            //.permitAll();     
    }   

I am not sure how to set the rest of the parameters (as done in XML) in this Java code for the WebSecurityConfig. Any help would be really appreciated

Pls try this :-

    @Bean
    public BaseLdapPathContextSource contextSource() {
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource("ldap://aaa:54389/dc=xxx.com");
    contextSource.setUserDn("bbb");
    contextSource.setPassword("ccc");
    return contextSource;
    }


        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.ldapAuthentication()
                .contextSource(contextSource())
                .and()
                .ldapAuthoritiesPopulator(new UmsLdapAuthoritiesPopulator(contextSource()))
                .and()
                .userSearchBase("").userSearchFilter("(&(uid={0})(objectclass=person)(ums-account-state=OK))");
         }            


    @Override
    protected void configure(HttpSecurity http) throws Exception {              
        http.authorizeRequests().antMatchers("/main/common**","/admincare**").hasRole("role.xyz.WebAdmin")
            .and().formLogin().loginPage("/auth/login").failureUrl("/auth/login?error=true").defaultSuccessUrl("/main/common")
            .and().logout().invalidateHttpSession(true).logoutSuccessUrl("/auth/login").logoutUrl("/auth/logout");    
    }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM