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

opu*_*tyk 2 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;
 }
Run Code Online (Sandbox Code Playgroud)

并且标头应用于此请求:

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');
      }
    });
 }
Run Code Online (Sandbox Code Playgroud)

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']);
          }
        });
    }
  }
Run Code Online (Sandbox Code Playgroud)

这是我的 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();
    }
Run Code Online (Sandbox Code Playgroud)

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

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

小智 5

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

你有没有尝试过

headers = headers.append("X-Requested-With", "XMLHttpRequest");
Run Code Online (Sandbox Code Playgroud)

append 不是直接附加标题而是返回一个新标题