Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  95] [ 1]  / answers: 1 / hits: 32302  / 6 Years ago, mon, may 7, 2018, 12:00:00

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?


More From » angular

 Answers
14

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.


[#54494] Wednesday, May 2, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hakeemabramh

Total Points: 234
Total Questions: 109
Total Answers: 109

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;