【问题标题】:Angular2 with spring boot LDAP authentication带有spring boot LDAP身份验证的Angular2
【发布时间】:2018-03-11 11:01:10
【问题描述】:

我在 Angular 2 中创建了登录页面,并希望在 Spring Boot 服务层使用 ldap 身份验证。我对这个概念很陌生。我已经编写了代码,但我不确定我在服务层的代码是否被调用。当我运行应用程序时,我得到“无法验证”,并且控制台上没有错误或日志语句。您能看看它并提供您的建议吗?

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

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;
                }
            });

服务层

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;
    }

【问题讨论】:

  • 改变你登录error =&gt; { console.log(error); } ,你不需要警报,所以至少你知道它是什么错误,还要检查你的服务器日志。

标签: angular authentication spring-security spring-security-ldap


【解决方案1】:

尝试在 Angular 主 app.module.ts

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


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

这应该将标头添加到您的 http 调用中。

那么你的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;
    }

希望它有效。

顺便说一句,我建议您在 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"));
}

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 2022-01-20
    • 2017-07-30
    • 2020-09-08
    • 1970-01-01
    • 2020-05-22
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多