In my angular application I have interceptor class like that:
import { Injectable, Inject, Optional, PLATFORM_ID } from '#angular/core';
import {
HttpInterceptor,
HttpHandler,
HttpRequest,
} from '#angular/common/http';
import { REQUEST } from '#nguniversal/express-engine/tokens';
import { isPlatformServer } from '#angular/common';
#Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(
#Inject(PLATFORM_ID) private platformId,
#Optional() #Inject(REQUEST) private request
) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (isPlatformServer(this.platformId)) {
req = req.clone({ headers: req.headers.set('Cookie', this.request.headers.cookie) });
}
return next.handle(req);
}
}
I am using Angular Universal server side rendering, so I take token from server and manually set in every API call which will be called by server. Everything works fine, but is it safe? I set token cookie manually inside every API request's header, maybe that's somehow risky?
I mayb be wrong, but I think it only matters if you send cookies to an API that you don't own, in which case you might be sending sensitive information to a 3rd party.
If you don't own the API, you could try parsing the cookies string (this.request.headers.cookie) and only pass the ones that the API need
Related
I am trying to set a new header on every http response so the response includes a content-security-policy using the latest version of angular. I have created this http interceptor, and when I go to add to the header I don't get any errors or anything, but nothing actually gets added to the response headers. Here is the code I have for the interceptor. Is there anything that I should change here, or is it not possible to add response headers to every http response from angular.
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse,
} from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { filter, map, tap } from 'rxjs/operators';
#Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
filter(event => event instanceof HttpResponse),
tap((event: HttpResponse<any>) => {
event.headers.append('content-security-policy', 'some content-security-policy')
})
);
}
}
You can not alter history: The network tab shows what was sent across the network, and you can not retroactively change that.
What an HttpInterceptor can do is change its own copy of the received headers before passing it on to the subscriber.
Also, a content security header is interpreted by the browser before it passes the response to JavaScript.
I try these code to connect my ionic app to apiserver (get)
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class EncryptionService {
url = 'https://api.am....com';
api-key='......'
constructor(private http: HttpClient) { }
newcheck(checkid: string ,cost: string,toname: string,tocode: string,passcode: string,date: string,checkfor: string,back: string): {
return this.http.get(`${this.url}?key=${this.api-key}&checkid=${encodeURI(checkid)}`);
}
}
my API has API key and get data in URL
how can i perform these in the secured way?
for example to prevent someone to listen and monitor transferred data between app and server?
prevent someone to distract and fake received data by app?
or, anything to make this connection secured
It looks like you're already using https which is encrypted.
A man in the middle attack should be prevented by default since browsers verify the certificate chain automatically.
I recommend reading this guide about https.
When I try to add a custom header along with a URL change (based on the environment), my custom header is not appending as part of the request headers.
Below is my HTTP Interceptor code (Angular 5):
import { Injectable } from '#angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '#angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let url = this.environment.api + request.url;
request = request.clone({
url: url,
setHeaders: {
Authorization: Bearer ${this.auth.getToken()}
}
});
return next.handle(request);
}
}
In the code above, if I remove the URL on request clone, I'm able to see my custom header as part of the request header. If I put a URL in the request.clone method, my custom header no longer adds to the request header. It adds a value of Access-control-Request-Header: authorization. Could someone help me on this?
Edit
Does we need do anything at server side to expose this custom header.If it is on same origin header is appending if it different origin it is not appending
I found the issue and the problem is at server side. When you hit a service which is running at different origin we need to set the custom header name at server side safe
cors header list. After updating the list at server side now I am able to see the header in request.
My question sounds similar to Cannot find the '#angular/common/http' module and Error loading #angular/common/http - angular 2 but the problem is a bit different:
I am using Angular 4.3.5 and I am trying to read data from a Web API. (This API puts out JSON data and is using SignalR and .net Core).
I have followed several tutorials and came up with this code for the class that will actually contact the service:
import 'rxjs/add/operator/map';
import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { Configuration } from './Configuration.js';
#Injectable()
export class DataService {
private actionUrl: string;
constructor(private http: HttpClient, private configuration: Configuration) {
this.actionUrl = configuration.serviceUrl;
}
//public getAll<T>(): Observable<T> {
// return this.http.get<T>(this.actionUrl);
//}
public getSingle<T>(id: number): Observable<T> {
return this.http.get<T>(this.actionUrl + id);
}
}
#Injectable()
export class CustomInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
console.log(JSON.stringify(req.headers));
return next.handle(req);
}
}
Now, building this project (I am using Visual Studio 2017 Enterprise) and running a gulp task to transpile the .ts to .js works just fine, so do all the intellisense-tooltips - the IDE does recognize the existance of those things.
But if I open it up in a browser (doesnt matter if firefox, edge or chrome) I get the following error:
zone.js:958 GET http://localhost:3966/libs/#angular/common/bundles/common.umd.js/http 404 (Not Found)
If I edit the transpiled javascript file by hand and write common-http.umd.js there, the file is found. (This is the reason why at the top I import Configuration.js instead of Configuration - it doesnt seem to want to automatically resolve the suffix, like in some tutorials).
I hope I am not too vague, since this is my first Time asking something publically. Also I was not able to find an answer in the given questions.
Well, I found a solution, for anybody who is curious why this and similar problems exist:
I had to edit my systemjs file and add this line:
'#angular/common/http': 'npm:#angular/common/bundles/common-http.umd.js',
and it works!
I've been stuck on an error that I'm not completely sure how to solve.
My application is made in Angular2 and runs completely in a webworker largely based on this tutorial http://www.syntaxsuccess.com/viewarticle/web-workers-in-angular-2.0
My first feature was an implementation of socket.io which is working perfectly(also with observables etc..) but now I want to use the Http service of Angular2 and I get the following error:
My code of the service is like this and the error arrises when I call validateAccessToken (I have to add the .js on my imports otherwise I get a 404 on the files within the webworker):
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from "#angular/http";
import { environment } from "../../../environments/environment.js";
import { Observable } from "rxjs/Observable.js";
import 'rxjs/add/operator/toPromise.js';
import 'rxjs/add/operator/map.js';
#Injectable()
export class AuthService {
headers: Headers;
options: RequestOptions;
url: string;
constructor(private http:Http) {
this.url = environment.authServerUrl;
}
validateAccessToken(token) {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleError);
};
extractData(response: Response) {...}
handleError(error: any) {...}
}
I know the question is quite vague but with the information I get from the error it's not really clear what's going wrong for me.
The CookieXSRFStrategy is default enabled by Angular2 and used by http.
The webworker does not have DOM access to get the cookie to insert in the http headers. And thus throws the error Uncaught not implemented.
You should implement your own CookieXSRFStrategy strategy which at least does not throw this error ;)