title: Spring Boot Security Ldap Rest Controller
body: <p>I am currently implementing RestControllers with Spring Security Ldap.</p>
  
  <p>The login is successful and the user informations are well returned.</p>
  
  <p>The problem is coming when the front end in angular wants to call my Rest api, the security returns unauthorised status. (should not as I am supposed to be logged in)</p>
  
  <p>I am new in spring security so maybe I am missing something simple in my configuration :)</p>
  
  <p>Here is some screenshots and configuration code sample (I erased some datas from the screenshots for confidential purposes) :</p>
  
  <p><a href="http://i.stack.imgur.com/PeW6M.png" rel="nofollow">GetDocuments Unauthorized</a></p>
  
  <p><a href="http://i.stack.imgur.com/jqUzz.png" rel="nofollow">GetDocuments unauthorised Details</a></p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(securedEnabled = true)
  @ComponentScan("com.*")
  @PropertySource(value= {"classpath:application.properties"})
  public class LdapSecurityConfig extends WebSecurityConfigurerAdapter {
  
  
      @Autowired
      private HttpAuthenticationEntryPoint authenticationEntryPoint;
      @Autowired
      private AuthSuccessHandler authSuccessHandler;
      @Autowired
      private AuthFailureHandler authFailureHandler;
      @Autowired
      private HttpLogoutSuccessHandler logoutSuccessHandler;
  
  
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @Bean
      @Override
      public UserDetailsService userDetailsServiceBean() throws Exception {
          return super.userDetailsServiceBean();
      }
  
      @Bean
      public AuthenticationProvider authenticationProvider() throws Exception {
  
          LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(getBindAuthenticator());
          ldapAuthenticationProvider.setUserDetailsContextMapper(new UserDetailsContextMapperImpl());
  
  
          return ldapAuthenticationProvider;
      }
  
      @Override
      protected AuthenticationManager authenticationManager() throws Exception {
          return super.authenticationManager();
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
  
                  http.authenticationProvider(authenticationProvider())
                      .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                  .and()
                      .csrf().disable()
                      .addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
                      .authorizeRequests().antMatchers(authorizeRequestsCurrentUser).permitAll()
                  .and()
                      .authorizeRequests().anyRequest().authenticated()
                  .and().rememberMe()
                  .and()
                      .formLogin()
                      .permitAll()
                      .loginProcessingUrl(loginProcessingUrl)
                      .usernameParameter(userNameParameter)
                      .passwordParameter(userPasswordParameter)
                      .successHandler(authSuccessHandler)
                      .failureHandler(authFailureHandler)
                  .and()
                      .logout().permitAll()
                      .deleteCookies("JSESSIONID")
                      .logoutRequestMatcher(new AntPathRequestMatcher(logoutRequestMatcher, RequestMethod.GET.name()))
                      .logoutSuccessHandler(logoutSuccessHandler)
                      .logoutSuccessUrl(logoutSuccessUrl)
                      .clearAuthentication(true)
                  .and()
                      .sessionManagement()
                      .maximumSessions(1);
      }
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  
              auth.eraseCredentials(false).authenticationProvider(authenticationProvider()).ldapAuthentication()
                  .userSearchFilter(ldapUserSearchFilter)
                  .groupSearchBase(ldapGroupSearchBase)
                  .userDetailsContextMapper(new UserDetailsContextMapperImpl())
                  .contextSource(getLdapContextSource());
      }
  
      private BindAuthenticator getBindAuthenticator()throws Exception{
          LdapContextSource contextSource = getLdapContextSource();
  
          String searchFilter=ldapSearchfilter;
          FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(ldapSearchBase, searchFilter,contextSource);
          userSearch.setSearchSubtree(true);
  
  
          BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource);
          bindAuthenticator.setUserSearch(userSearch);
          bindAuthenticator.afterPropertiesSet();
  
          return bindAuthenticator;
      }
  
      private LdapContextSource getLdapContextSource() throws Exception {
          LdapContextSource cs = new LdapContextSource();
          cs.setUrl(ldapUrl);
          cs.setBase(ldapBase);
          cs.setUserDn(ldapUserDn);
          cs.setPassword(ldapPassword);
          cs.setPooled(true);
          cs.afterPropertiesSet();
          return cs;
      }
  
  }
  
  
  
  @Component
  @Log4j
  public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
      private final ObjectMapper mapper;
  
      @Autowired
      AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) {
          this.mapper = messageConverter.getObjectMapper();
      }
  
      @Override
      public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                          Authentication authentication) throws IOException, ServletException {
  
          LdapUser authUser = (LdapUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  
          MyUser user = new MyUser();
          user.setUsername(authUser.getUsername());
          user.setPassword(cred);
  
          // set our response to OK status
          response.setStatus(HttpServletResponse.SC_OK);
          response.setContentType(MediaType.APPLICATION_JSON_VALUE+"; charset=UTF-8");
  
          PrintWriter writer = response.getWriter();
          mapper.writeValue(writer, authUser);
          writer.flush();
      }
  }
  
  
  
  
  public class CORSFilter  implements Filter{
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
      }
  
      @Override
      public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
          HttpServletResponse response = (HttpServletResponse) res;
          response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true");
          response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
          response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, OPTIONS, DELETE");
          response.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");
          response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "x-requested-with");
          chain.doFilter(request, response);
      }
  
      public void destroy() {}
  }
  
  
  
  @Component
  public class UserDetailsContextMapperImpl extends LdapUserDetailsMapper {
  
      @Override
      public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
                                            Collection&lt;? extends GrantedAuthority&gt; authorities) {
          UserDetails userDetails= super.mapUserFromContext(ctx,username,authorities);
          String fullName = ctx.getStringAttribute("givenName");
          String email = ctx.getStringAttribute("mail");
          return new LdapUser((LdapUserDetails)userDetails,fullName,email);
      }
  }
  
  
  @Log4j
  @CrossOrigin
  @RestController
  @ComponentScan("com.*")
  @RequestMapping(value = "${config.rest.uri.entry.path}", produces = MediaType.APPLICATION_JSON_VALUE)
  public class DashboardController {
  
      @Autowired
      IDashboardService dashboardService;
  
      @RequestMapping(value = "${config.rest.uri.dashboard.documents}",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
      public Result&lt;List&lt;DashboardDocument&gt;&gt; getDocumentList(@RequestParam(value="username") String username){
  
  
       ----------------
  
          return result;
      }
  }
  </code></pre>