2017-02-13 105 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