how to achieve Ldap Authentication using spring security(spring boot)

夙愿已清 提交于 2021-02-10 04:15:31

问题


I have following code with me I am trying to achieve ldap Authentication but i think it is not happening.

My Security Configuration

@EnableWebSecurity
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class Config extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.httpBasic().and().authorizeRequests().antMatchers("/*")
                .permitAll().anyRequest().authenticated().and().csrf()
                .disable().httpBasic().and().csrf()
                .csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.ldapAuthentication()
                .userSearchFilter("(uid={0})")
                .userSearchBase("dc=intern,dc=xyz,dc=com")
                .contextSource()
                .url("ldap://192.168.11.11:1234/dc=intern,dc=xyz,dc=com")
                .managerDn("username")
                .managerPassword("password!")
                .and()
                .groupSearchFilter("(&(objectClass=user)(sAMAccountName=" + "username" + "))");

    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                    HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request
                        .getAttribute(CsrfToken.class.getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null
                            && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                        response.sendRedirect("/notAllowed");
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
}

My Controller

    @RequestMapping(value = { "/test" }, method = RequestMethod.GET)
public @ResponseBody String retrieve() {
    System.out.println("line 1");
    System.out.println("line 2");
    return "hello";

}

@RequestMapping(value = { "/notAllowed" }, method = RequestMethod.GET)
public @ResponseBody HttpStatus login() {

    return HttpStatus.FORBIDDEN;

}

i am aiming for :

i want to achieve ldap authentication. Username and password will come from browser though i have tried with hardcoded username and password as well.

if user is authentic then filter will check the authorizátion by checking the token .

if this is first request then new token will be generated and sent. if its not found then it will send the HTTP Status forbidden.

I have following problems :

  1. when i run first time from browser it returns forbidden but it also prints "line 1 and line 2" in console though it do not return hello but forbidden.

  2. are my htpSecurity and ldap Configuration fine?.

  3. from 2nd request it always return hello , i have tried to open new tab ,new request but still it works fine .If i restart server then only it generates token and compare it with cookies token.what if two people are using same system (different times).

  4. how exactly i can test ldap authentication ? i am using POSTMAN as a client .

If some information is missing from my end please let me know . And i will be thankful for your answers.


回答1:


First of all, I think your HttpSecurity config is wrong. You want to protect ALL the endpoints. Don't you?

So change it to the following:

http.httpBasic()
        .and()
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .csrf()
        .csrfTokenRepository(csrfTokenRepository())
        .and()
        .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);

Furthermore, I'm not sure whether your ldap config is right. I think you can reduce it to the following:

auth.ldapAuthentication()
        .userSearchFilter("uid={0}")
        .contextSource()
        .url("ldap://192.168.11.11:1234/dc=intern,dc=xyz,dc=com");

Make sure if your userSearchBase is right. It doesn't have an "ou".

If you don't have any different organizational units, you can simply remove the userSearchBase

To provide better help i need to know the structure of your ldap.

If you want to check your HttpSecurity config you may not use ldap in the first place and use inMemoryAuthentication instead:

auth.inMemoryAuthentication().withUser("user").password("password").authorities("ROLE_USER");


来源:https://stackoverflow.com/questions/32757440/how-to-achieve-ldap-authentication-using-spring-securityspring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!