Angular 4.3 HTTPClient 基本授权不起作用

2022-09-01 19:04:49

我正在尝试在使用新发布的.Angular 4HttpClient

我正在尝试连接到运行的应用程序,该应用程序具有公开的API。SpringTomcatREST

我的:LoginComponent

onSubmit(user){
   console.log(user);
   const body = JSON.stringify({username: user.userName, password: user.password});

   let headers = new HttpHeaders();
   headers.append("Authorization", "Basic " + btoa("username:password"));
   headers.append("Content-Type", "application/x-www-form-urlencoded");

   this.http.post('my url here',body, {headers: headers}).subscribe(response => {
         console.log(response);
   }, err => {
      console.log("User authentication failed!");
   });
}

但是,请求根本不添加标头。Authorization

这是从工具选项卡:ChromeNetwork

enter image description here

我做错了什么?我怎样才能做到这一点?


更新1:它仍然不起作用:

我更改了我的两行,如下所示:

headers = headers.append("Authorization", "Basic " + btoa("username:password"));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");

我按预期在请求中获取标头。这是从 :Chrome

enter image description here

但是,发布呼叫仍然失败。

在服务器端,我的代码是:

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String authCredentials = request.getHeader("Authorization");

    if(authCredentials == null) {
        logger.info("Request with no basic auth credentials {}", request.getRequestURL());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    // do my stuff
}

呼叫永远不会到达 。 是。do my stuffauthCredentialsnull

这是从 :chrome

enter image description here

如何进行?


答案 1

HttpHeaders是不可变的,因此您需要分配函数的结果以覆盖每次调用的对象。headers

let headers = new HttpHeaders();
headers = headers.append("Authorization", "Basic " + btoa("username:password"));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");

来源: Angular Docs


答案 2

嗨,您的后端配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class RestConfig {
    @Bean
    public CorsFilter corsFilter() {
         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
     }
 }

你的角度要求应该是这样的,

import { Http , Headers, Response } from '@angular/http';
let headers = new Headers();
headers.append("Authorization", "Basic " + btoa("username:password"));
headers.append("Content-Type", "application/x-www-form-urlencoded");

您还可以使用angular2/4检查githup回购示例演示弹簧mvc


推荐