【问题标题】:Spring Security can't see credentials passed by AngularSpring Security 看不到 Angular 传递的凭据
【发布时间】:2019-10-01 17:50:50
【问题描述】:

我尝试使用 spring security 基本授权。当我从 Angular 发出发布请求时,spring 无法识别“用户名”和“密码”属性。当我向邮递员发出邮寄请求时,它可以工作。我不知道问题出在弹簧配置还是角度请求上。

我已经尝试了许多发布请求的配置,但没有任何效果。

这是我的 spring 安全配置:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("a").password("a").roles("*");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().
                csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/users").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().and().httpBasic();
    }

我最新的角度发布请求:

constructor(private httpClient: HttpClient) {}

  handleLogin(user: UserDto) {

    let headers = new HttpHeaders({
      'Authorization': 'Basic ' + btoa('a' + ':' + 'a'),
       'X-Requested-With': 'XMLHttpRequest'
});
    this.httpClient
      .post("//localhost:8080/login" ,{}, {headers}).subscribe(x=> {console.log(x)});
  }

这是spring安全检查凭证和结果为空的地方

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String username = this.obtainUsername(request); //null
            String password = this.obtainPassword(request); //null

当我从邮递员授权工作发出帖子请求时,我希望有人可以帮助我通过角度请求获得语义结果。

-----------编辑---------- 正如评论中所建议的,我尝试了这个,但仍然是同样的问题。

let options = { headers: headers };
this.httpClient
  .post("//localhost:8080/login", {}, options).subscribe(x => { console.log(x) });

谢谢

【问题讨论】:

  • 您想使用 HTTP 基本登录还是表单登录?我猜您不想要表单登录,因此您应该删除表单登录配置或至少调用另一个 URL(/login 仅用于表单登录,不支持 HTTP 基本)。

标签: angular spring-security authorization


【解决方案1】:

对于 HttpClient.post,第二个参数应该是请求正文,然后是选项。

可能会添加

let options = { headers: headers };
this.httpClient.post(url, null, options);

https://v4.angular.io/api/common/http/HttpClient#post

4.3 之前的 Angular 版本有一个旧的 http api,其中包含一组不同的参数,可能会让您感到困惑。

【讨论】:

  • 感谢您的回复,不幸的是不起作用,请检查我的编辑
猜你喜欢
  • 2017-07-27
  • 2019-01-05
  • 2015-08-31
  • 2011-07-15
  • 1970-01-01
  • 2021-03-25
  • 2015-01-26
  • 2020-02-01
相关资源
最近更新 更多