typescript 带有凭据的 Angular 6 httpClient Post

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50210662/
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-10-21 05:23:42  来源:igfitidea点击:

Angular 6 httpClient Post with credentials

javascriptangulartypescriptangular6

提问by mobby

I have some code which posts some data to create a data record.

我有一些代码可以发布一些数据来创建数据记录。

It's in a service:

它在一个服务中:

Here's the code:

这是代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  create() {
      const postedData = { userid: 1, title: 'title here', body: 'body text' };
      return this.http.post('https://jsonplaceholder.typicode.com/posts', postedData, httpOptions).subscribe(result => {
        console.log(result);
      }, error => console.log('There was an error: '));
  }

}

My question is...what do I do what the url requires from the user to be logged in...How do I pass the credentials?

我的问题是...我该怎么做 url 要求用户登录...如何传递凭据?

采纳答案by TanguyB

Well, in order to secure your endpoints, you must first choose the strategy on how to sign your calls and for them to be secure. A common method would be using JWT Tokens. (There are other alternatives, I'm offering you the one I'm most familiar with).

好吧,为了保护您的端点,您必须首先选择有关如何签署您的呼叫并确保它们安全的策略。一种常见的方法是使用 JWT 令牌。(还有其他选择,我为您提供了我最熟悉的一个)。

This would require the user to contact an endpoint on your backend, unsecured, with their credentials. You need to configure your backend, which will check the credentials, and if they are correct the backend will give you back a token, which you will use to sign your secure calls ( with JWT, you put this token in your header, if your backend is configured correctly, it will check for this token on the secured APIs).

这将要求用户使用他们的凭据联系您后端的端点,不安全。你需要配置你的后端,它会检查凭据,如果它们是正确的,后端会给你一个令牌,你将用它来签署你的安全调用(使用 JWT,你把这个令牌放在你的标头中,如果你后端配置正确,它将在安全 API 上检查此令牌)。

As we don't know what backend you use, I can only recommend you a library for JWT tokens in angular for your frontend. https://github.com/auth0/angular-jwt

由于我们不知道您使用什么后端,我只能为您推荐一个用于前端的 JWT 令牌库。https://github.com/auth0/angular-jwt

This library will give you a http client that will automatically sign your request with a token if you've stored one locally. It also allows you to, put guards on your frontend urls, which will also automatically check if the token stored is not expired for example.

该库将为您提供一个 http 客户端,如果您在本地存储了一个令牌,它会自动使用令牌对您的请求进行签名。它还允许您在前端 url 上设置保护,例如,它还将自动检查存储的令牌是否未过期。

The workflow would be as follow:

工作流程如下:

1) User sends credentials to backend

1) 用户向后端发送凭据

2) Backend confirms credentials and sends back a token

2)后端确认凭据并发回令牌

3) You store your token in a local storage in your frontend, and configure the library to use it.

3) 您将令牌存储在前端的本地存储中,并配置库以使用它。

4) Set guards on secured URLs, as a pre-check on wether you have a non expired token or not.

4) 对受保护的 URL 设置保护,作为对您是否有未过期令牌的预检查。

5) Finally use the library's HTTP Client, which will sign your requests with the token you've stored in your local storage, which will be needed to consume your secured API.

5) 最后使用库的 HTTP 客户端,它将使用您存储在本地存储中的令牌对您的请求进行签名,这将需要使用您的安全 API。

EDIT:

编辑:

I've a basic template which uses JWT tokens in Angular. You can find it here https://github.com/BusschaertTanguy/angular2_template/.

我有一个在 Angular 中使用 JWT 令牌的基本模板。你可以在这里找到它https://github.com/BusschaertTanguy/angular2_template/

Look in the auth module for configuration, login & register component, http client for the secured http client, auth & auth-guard service for token handling & route guarding.

在 auth 模块中查找配置、登录和注册组件、用于安全 http 客户端的 http 客户端、用于令牌处理和路由保护的 auth 和 auth-guard 服务。

Some quick snippets from the template to help you out:

模板中的一些快速片段可以帮助您:

//Library Configuration
export function authHttpServiceFactory(
  http: Http,
  options: RequestOptions
) {
  return new AuthHttp(
    new AuthConfig({
      tokenName: 'token',
      tokenGetter: (() => localStorage.getItem('token')),
      globalHeaders: [{ 'Content-Type': 'application/json' }]
    }),
    http,
    options
  );
}

@NgModule({
  providers: [{
    provide: AuthHttp,
    useFactory: authHttpServiceFactory,
    deps: [Http, RequestOptions]
  }]
})
export class AuthModule { }


//HttpService
get(url: string): Observable<any> {
    return this.http.get(endpoint).map(data => data.json());
  }


//LoginComponent
login() {
    this.httpService.get(urlToLogin).subscribe(
      data => {
        localStorage.setItem('token', data.access_token);
      }
    );
}

Those are the places to look for your frontend configuration, you can also follow the tutorial on the library's page, as it's the way I implemented it, only I added some abstractions here and there, just to give you an idea of where to start.

这些是查找前端配置的地方,您也可以按照库页面上的教程进行操作,因为这是我实现它的方式,只是我在这里和那里添加了一些抽象,只是为了让您知道从哪里开始。

回答by mobby

In order to request with cookies you will need to add withCredentialsin your request. See following code

为了使用 cookie 进行请求,您需要在请求中添加withCredentials。看下面的代码

const httpOptions = {
 headers: new HttpHeaders({
  'Authorization': fooBarToken
 }),
 withCredentials: true
};

回答by devpato

The following code works too:

以下代码也有效:

return this.http.get<{}>('YOU API URL', {
      withCredentials: true
 })