为Angular 2配置Spring安全性

时间:2017-02-13 17:38:04

标签: angular spring-security

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

My Angular对身份验证的要求:

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

身份验证失败并显示错误:

  

{"时间戳":1487007177889,"状态":401,"错误":"未授权""消息&# 34;:"身份验证失败:空用户名","路径":" / 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
    }
}

1 个答案:

答案 0 :(得分:1)

您应该使用application/x-www-form-urlencoded参数进行表单登录,而不是JSON。这就是错误导致用户名丢失的原因,因为Spring Security试图从HttpServletRequest#getParameters中获取用户名。要在Angular中发送表单参数,您可以执行

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

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

如果你把它设置为Http请求的body参数,它应该(从我记忆中)自动被序列化为正确的格式,即

username=xxx&password=xxx

我认为您不需要将标头Content-Type设置为applicatio/x-www-form-urlencoded。我认为,当Angular将URLSearchParams视为正文时,也应该为您设置。