我在Angular 2中创建了登录页面,并希望在spring启动服务层使用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;
});
}
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;
}
答案 0 :(得分:1)
尝试在Angular主要 app.module.ts
中添加XSRFStrategyexport 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"));
}