为Angular 2配置Spring安全性 [英] Configure Spring security for Angular 2

查看:73
本文介绍了为Angular 2配置Spring安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a Angular 2 web client that tries to do a POST to a server using SpringBoot Security. How should I write my Spring security configuration?

我的Angular身份验证电话:

My Angular call for authentication:

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

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

The authentication fails with the error:

{时间戳":1487007177889,状态":401,错误":未经授权",消息":身份验证失败:空用户名",路径":"/登录"}

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

我的spring安全配置:

My spring security configuration:

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

推荐答案

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

You're supposed to use application/x-www-form-urlencoded parameters for form login, not JSON. That's why the error is saying that the username is missing, because Spring Security it trying to get it from the HttpServletRequest#getParameters. To send form parameters in Angular, you can do

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

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

如果将其设置为Http请求的主体参数,则应该(据我所记得)会自动序列化为正确的格式,即

If you set it as the body parameter of the Http request, it should (from what I remember) automatically be serialized to the correct format, i.e.

username=xxx&password=xxx

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

And I don't think you need to set the header Content-Type to applicatio/x-www-form-urlencoded either. I think that should also be set for you when Angular detects URLSearchParams as the body.

这篇关于为Angular 2配置Spring安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆