如何禁用浏览器基本身份验证弹出窗口 - Angular 5 + Spring Security

时间:2018-03-04 16:40:40

标签: java spring spring-security basic-authentication angular5

我遇到浏览器弹出的基本身份验证问题。尽管Angular中有登录表单,但在输入凭据并单击登录按钮后,浏览器会创建基本身份验证弹出窗口。当我在浏览器弹出窗口中登录时,一切正常。在每个请求中都有以下标题:

private createLoginHeaders(email: string, password: string): Headers {
    let headers: Headers = new Headers();
    headers.append("Authorization", "Basic " + btoa(email + ":" + password));
    headers.append("Content-Type", "application/x-www-form-urlencoded");
    headers.append("X-Requested-With", "XMLHttpRequest");

    return headers;
 }

标题将应用于此请求:

login(email: string, password: string): Observable<User> {
    let headers = this.createLoginHeaders(email, password);

    return this.http.post<User>(`api/user/secure/current`, {headers: headers}).do(
      (user: User) => {
        this.saveUserToLocalStorage(user);
      }
    ).catch(err => {
      if (err.status === 401) {
        return Observable.throw('Unauthorized');
      }
    });
 }

当我得到响应而不改变observable中的任何内容时,Do()函数可以做某事。以下是上述代码的使用者方法:

 login(email: string, password: string) {
    if(!this.authenticationService.isAuthenticated()) {
      this.authenticationService.login(email, password).subscribe(
        () => {
          this.router.navigate(['librarian']);
        }, (err) => {
          if(err === "Unauthorized") {
            this.router.navigate(['login']);
          }
        });
    }
  }

这是我的spring安全配置:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                    .antMatchers("/**/secure/**").authenticated()
                    .anyRequest().permitAll()
                .and()
                    .logout()
                    .logoutUrl("/secure/logout")//I add '/api' to every request by setting this option in spring properties
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true)
                    .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
                    .permitAll()
                .and()
                    .httpBasic()
                .and()
                    .cors()
                .and()
                    .csrf()
                    .disable();
    }

此外,Angular和Spring Web应用程序位于不同的端口上(Angular localhost:4200,Spring localhost:8080)。这就是我在Spring应用程序中使用CORS配置和在Angular应用程序中使用proxy.conf.json的原因。

你有什么想法吗?如果需要,我还可以显示其他一些代码片段。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

如果您在发送错误的凭据时遇到登录弹出窗口的问题,可能是因为您的标头。

您尝试过

headers = headers.append("X-Requested-With", "XMLHttpRequest");

append不是直接附加标题,而是返回新的标题

相关问题