Angular 6 httpClient Post with credentials

时光总嘲笑我的痴心妄想 提交于 2021-02-18 06:40:06

问题


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?


回答1:


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).

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).

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

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.

The workflow would be as follow:

1) User sends credentials to backend

2) Backend confirms credentials and sends back a token

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

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

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.

EDIT:

I've a basic template which uses JWT tokens in Angular. You can find it here 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.

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.




回答2:


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

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



回答3:


The following code works too:

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


来源:https://stackoverflow.com/questions/50210662/angular-6-httpclient-post-with-credentials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!