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

查看:93
本文介绍了带有凭证的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: '));
  }

}

我的问题是...我该怎么做才能从用户登录时获得该网址的要求...我如何传递凭据?

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天全站免登陆