简体   繁体   English

带有 Spring Boot LDAP 身份验证的 Angular2

[英]Angular2 with spring boot LDAP authentication

I created login page in Angular 2 and want to use ldap authentication at the spring boot service layer.我在 Angular 2 中创建了登录页面,并希望在 Spring Boot 服务层使用 ldap 身份验证。 i am very new to this concept.我对这个概念很陌生。 I had written the code but i am not sure whether my code at service layer is getting called or not.我已经编写了代码,但我不确定我在服务层的代码是否被调用。 When i run the application i am getting "could not authenticate" and no error or log statements at the console.Can you please take a look at it and provide your suggestions ?当我运行该应用程序时,我收到“无法进行身份验证”并且控制台上没有错误或日志语句。您能看一下它并提供您的建议吗?

login.component.ts
----------------------
login(username:string , password:string) {
 if(username != '' && password != ''){
 if(!username.endsWith('@abc.com')){
            username += '@abc.com';
          }

this.loading = true;
 this.authService.login(username, password)
           .subscribe(
                data => {
                    this.router.navigate(['./jobcleanup/home']);
                },
                error => {

                   alert("could not authenticate");
                    this.loading = false;
                });
}

auth.service.ts auth.service.ts

login(username: string, password: string): Observable<boolean> {
    alert('inside authservice login');
      let headers = new Headers({ 'Content-Type': 'application/json' });
      let options = new RequestOptions({ headers: headers });
       let body = {"username": username, "password": password};
        return this.http.post('http://localhost:8080/login', body ,options)
            .map((response: Response) => {
                let token = response.json() && response.json().token;
                if (token) {
                    this.token = token;
                       localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));
                    return true;
                } else {
                    return false;
                }
            });

Service Layer服务层

Rest Controller



@CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping("/login")
    public String loginForm(Model model){
        logger.info("Login Form");
        return "login";

    }
AuthConfig
-----------------

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .authorizeRequests()
                .antMatchers("/login*").anonymous()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("*"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }


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

    @Override
    protected UserDetailsService userDetailsService() {
        return userDetailsService;
    }


    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
    }

    @Bean
    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {

        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("abc.com", "ldap://ldap.abc.com:389");
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        provider.setUserDetailsContextMapper(userDetailsContextMapper);
        return provider;
    }

Try adding XSRFStrategy in Angular main app.module.ts尝试在 Angular 主app.module.ts 中添加XSRFStrategy

export function xsrfFactory() { return new CookieXSRFStrategy('XSRF-TOKEN', 'x-xsrf-token'); }


...
providers : [
  { provide: XSRFStrategy, useFactory: xsrfFactory },
]

this should add the header to your http calls.这应该将标头添加到您的 http 调用中。

Then your change Spring configuration like this然后你像这样改变Spring配置

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

   http.csrf().csrfTokenRepository(csrfTokenRepository()).ignoringAntMatchers("/login/**");    

    // @formatter:off
    http.authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/api/**").authenticated() // your rest api here
        .antMatchers("/login/**").permitAll()
        .anyRequest().authenticated();
    // @formatter:on

    http.logout().logoutSuccessUrl("/");

}


    @Bean
    public CsrfTokenRepository csrfTokenRepository() {
        CookieCsrfTokenRepository repository = new CookieCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        repository.setCookieHttpOnly(false);
        return repository;
    }

Hopefully it works.希望它有效。

By the way I'd suggest testing your security config in Spring with an integration test first , try something like this顺便说一句,我建议使用集成测试在 Spring 中测试您的安全配置,尝试这样的操作

@Test
public void testWebApplicationContext_httpSecurityUnathorisedAccess_exceptionHandling() throws Exception {
    mockMvc.perform(get("/info").contentType(APPLICATION_JSON_UTF8)).andExpect(status().isUnauthorized());
}

@Test
@WithMockUser(username = "user.something", authorities = { "view"})
public void testWebApplicationContext_httpSecurityAuthorisedAccess_ok() throws Exception {
    mockMvc.perform(get("/info").contentType(APPLICATION_JSON_UTF8)).andExpect(status().isOk())
            .andExpect(model().attributeExists("username")).andExpect(view().name("info"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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