Java Angular 4.3 HTTPClient 基本授权不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45894628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:13:29  来源:igfitidea点击:

Angular 4.3 HTTPClient Basic Authorization not working

javaspringangulargoogle-chrometomcat

提问by Vicky

I am trying to implement basic authorization in Angular 4using the newly released HttpClient.

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

I am trying to connect to a Springapplication running on Tomcatwith exposed RESTAPIs.

我正在尝试连接到使用公开APISpring运行的应用程序。TomcatREST

I have the following code in my LoginComponent:

我的代码中有以下代码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!");
   });
}

However, the request does not add Authorizationheader at all.

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

This is from the Chrometools Networktab:

这是来自Chrome工具Network选项卡:

enter image description here

在此处输入图片说明

What am I doing wrong ? How can I make this work ?

我究竟做错了什么 ?我怎样才能使这项工作?



Update 1: Its still not working:

更新 1:它仍然无法正常工作:

I changed my two lines as below:

我改变了我的两行如下:

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

I am getting header in the request as expected. This is from Chrome:

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

enter image description here

在此处输入图片说明

However, the post call is still failing.

但是,post 调用仍然失败。

At server side, my code is:

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

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
}

Call is never reaching do my stuff. authCredentialsis null.

呼叫永远不会到达do my stuffauthCredentialsnull

This is from chrome:

这是来自chrome

enter image description here

在此处输入图片说明

How to proceed ?

如何进行 ?

采纳答案by Ben Kolya Mansley

HttpHeadersis immutable, so you need to assign the result of the function to override the headersobject each call.

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

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

Source: Angular Docs

来源:Angular 文档

回答by Robert

Hi can your backend cors configuration

嗨,您的后端 cors 配置可以吗

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

Your angular request should be like that,

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

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

You can also check githup repo sample demo spring mvc with angular2/4

您还可以使用 angular2/4检查 gitup repo 示例演示 spring mvc

回答by Ajit Soman

Use RequestOptionsto set headers to your post request.

用于RequestOptions为您的发布请求设置标头。

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

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

回答by Mohammad Anas

I was having the same problem and authorization header was not going with post request. This was my authenticate function

我遇到了同样的问题,并且授权标头不适用于发布请求。这是我的身份验证功能

authenticate(username, password) {
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ':' + password) });

return this.httpClient.post<any>('<your-login-url>',{headers}).pipe(
 map(
   userData => {
    sessionStorage.setItem('username',username);
    return userData;
   }
 )
);

I did not know that post requires second argument as body and third as headers. After coming this question I found it from question itself that I need to send a second argument as blank json because I dont have anything in body.

我不知道 post 需要第二个参数作为正文,第三个参数作为标题。提出这个问题后,我从问题本身中发现,我需要将第二个参数作为空白 json 发送,因为我体内没有任何东西。

And here is the correct code for above authenticate function

这是上述身份验证功能的正确代码

authenticate(username, password) {
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ':' + password) });

return this.httpClient.post<any>('<your-login-url>',{},{headers}).pipe(
 map(
   userData => {
    sessionStorage.setItem('username',username);
    return userData;
   }
 )
);

Which is working fine now.

现在工作正常。