0

I haven't tried anything all i have is http post method, i need to pass the username and password as base authentication to every API i am hitting

onSubmit = function(userdata){
     this.tokenkey = localStorage.getItem('logintoken');

  console.log(JSON.stringify(userdata));
this.pass=
{
  "foodid": userdata.foodid,
  "foodname": userdata.foodname,
  "state" : userdata.state,
  "station" : userdata.station,
  "district" : userdata.district,
  "zipcode" : userdata.zipcode,
  "country" : userdata.country,
  "description" : userdata.description,

}
 this.http.post(SERVER_URL+'fooddata/add',this.pass).subscribe((Response) => {
   console.log(Response);
 if(Response.ok === true){
    this.Success();
    this.temp = {};
    this.userdata.reset();
  }
 else this.Error();
})

}

Any help on how to pass authentication header in this API ?

stephen
  • 9
  • 1
  • Does this answer your question? [Angular 6 - httpClient passing basic auth in httpOptions](https://stackoverflow.com/questions/50694913/angular-6-httpclient-passing-basic-auth-in-httpoptions) – R. Richards Sep 27 '20 at 12:34
  • Hi Richards, So i need to add that Http options in the post method and also would it be useful in angular 4 ? – stephen Sep 27 '20 at 12:45
  • 1
    Depends. Are you using `HttpClient`, or `Http` to do your `post`? If you are using `Http`, then no, otherwise, yes. – R. Richards Sep 27 '20 at 12:53
  • okay Richards, but the actual output i'm expecting is, once i logged in when i copy the url of any page inside the application and paste it another tab, the page shouldn't come instead it should show authorization error, would this answer gives that output ? – stephen Sep 27 '20 at 12:58
  • You should try it and see if that is the behavior you get. – R. Richards Sep 27 '20 at 13:39
  • I've tried but the page is laoding in the another tab and i'm not getting the authorization error on the next tab where I'm pasting the url of the page, any help ? – stephen Sep 27 '20 at 13:59

1 Answers1

0

You can create an interceptor that adds the authentication header key-value pair(s) to every request you make. This kind of task is the perfect candidate for Http Interceptors. Check this page and this page.

Here is an example:

@Injectable({
    providedIn: 'root',
})
export class CustomInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let params = req.params.set('custom-header-name', 'custom-header-value');
        return next.handle(req.clone( { params } ));
    }
}

Now, provide this interceptor it in your module where you have imported HttpClientModule or any other module:

providers: [{provide: HTTP_INTERCEPTORS, useClass: CustomInterceptor}]
user2007130
  • 366
  • 3
  • 8