2017-02-13 107 views
1

我正在构建一个Angular 2 Web客户端,该客户端尝试使用SpringBoot Security向服务器执行POST。我应该如何编写我的Spring安全配置?为Angular 2配置Spring安全性

我的角度呼吁验证:

public login(username, password) { 
    let body = JSON.stringify({username: username, password: password}); 
    let headers = new Headers({'Content-Type': 'application/json'}); 
    let options = new RequestOptions({headers: headers}); 
    this.http.post("http://localhost:8080/login", body, options) 
    .subscribe(
     res => this.loggedIn = true, 
     err => console.error("failed authentication: " + err), 
    () => console.log("tried authentication") 
    ); 
} 

身份验证失败,出现错误:

{"timestamp":1487007177889,"status":401,"error":"Unauthorized","message":"Authentication Failed: Empty Username","path":"/login"}

我春天的安全配置:

@Configuration 
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {  
    @Autowired 
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint; 
    @Autowired 
    private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler; 
    @Autowired 
    private RestAuthenticationFailureHandler restAuthenticationFailureHandler; 
    @Autowired 
    private RestLogoutSuccessHandler restLogoutSuccessHandler; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable() 
       .exceptionHandling() 
       .authenticationEntryPoint(restAuthenticationEntryPoint) 

       .and().formLogin() 
       .loginProcessingUrl("/login") 
       .usernameParameter("username") 
       .passwordParameter("password") 
       .successHandler(restAuthenticationSuccessHandler) 
       .failureHandler(restAuthenticationFailureHandler) 
       .permitAll() 

       .and().logout() 
       .logoutUrl("/logout") 
       .logoutSuccessHandler(restLogoutSuccessHandler) 
       .permitAll() 

       .and().authorizeRequests().anyRequest().authenticated() 
     ; 
    } 

    @Override 
    public void configure(AuthenticationManagerBuilder builder) throws Exception { 
     // This configuration has been tested, it works. 
     // It has been removed for better readability 
    } 

    @Bean 
    public LdapContextSource contextSource() { 
     // This configuration has been tested, it works. 
     // It has been removed for better readability 
    } 
} 
+0

看起来像一个春天的问题。我在你的Angular代码中看不到任何错误。 – AngularChef

回答

1

你应该使用application/x-www-form-urlencoded表单登录参数,而不是JSON。这就是为什么错误是说缺少用户名,因为Spring Security试图从HttpServletRequest#getParameters中获取它。要发送的角形式参数,你可以做

import { URLSearchParams } from '@angular/http'; 

let params = new URLSearchParams(); 
params.set('username', username); 
params.set('password', password); 

如果你将其设置为HTTP请求的身体参数,它应该(从我记得)自动序列化到正确的格式,即

username=xxx&password=xxx 

而且我不认为您需要将标头Content-Type设置为applicatio/x-www-form-urlencoded。我觉得Angular在检测到URLSearchParams时应该为你设置。

+0

这个伎俩,非常感谢。 man'URLSearchParam',什么?那有多直观? –

+0

它也用于查询字符串。我猜这个名字更有意义 –

+0

'URLSearchParams'不能用于Webkit – Anatoly