带有凭据的 Angular 6 httpClient Post [英] Angular 6 httpClient Post with credentials

查看:23
本文介绍了带有凭据的 Angular 6 httpClient Post的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

它在一个服务中:

代码如下:

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

}

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

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

推荐答案

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

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,你把这个令牌放在你的标头中,如果你后端配置正确,它将在安全 API 上检查此令牌).

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 令牌库.https://github.com/auth0/angular-jwt

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

这个库会给你一个 http 客户端,如果你在本地存储了一个令牌,它会自动用一个令牌签署你的请求.它还允许您在前端 url 上设置保护,例如,它还会自动检查存储的令牌是否未过期.

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.

工作流程如下:

1) 用户向后端发送凭据

1) User sends credentials to backend

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

2) Backend confirms credentials and sends back a token

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

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

4) 对受保护的 URL 设置保护,以预先检查您是否拥有未过期的令牌.

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

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

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.

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

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

在auth模块中查看配置,登录&注册组件,用于安全 http 客户端的 http 客户端,auth &用于令牌处理的 auth-guard 服务路线守卫.

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.

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

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.

这篇关于带有凭据的 Angular 6 httpClient Post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆