Commit b4729073 authored by AllForNothing's avatar AllForNothing
Browse files

Change storage of csrf token from cookie to localstorage


Signed-off-by: default avatarAllForNothing <sshijun@vmware.com>
parent 05afb94b
import { TestBed, inject } from '@angular/core/testing';
import { InterceptHttpService } from './intercept-http.service';
import { CookieService } from 'ngx-cookie';
import { HttpRequest, HttpResponse } from '@angular/common/http';
import { of, throwError } from 'rxjs';
describe('InterceptHttpService', () => {
let cookie = "fdsa|ds";
const mockCookieService = {
get: function () {
return cookie;
},
set: function (cookieStr: string) {
cookie = cookieStr;
}
};
const mockedCSRFToken: string = 'test';
const mockRequest = new HttpRequest('PUT', "", {
headers: new Map()
});
......@@ -29,13 +19,21 @@ describe('InterceptHttpService', () => {
}
}
};
beforeEach(() => TestBed.configureTestingModule({}));
beforeEach(() => {
let store = {};
spyOn(localStorage, 'getItem').and.callFake( key => {
return store[key];
});
spyOn(localStorage, 'setItem').and.callFake((key, value) => {
return store[key] = value + '';
});
spyOn(localStorage, 'clear').and.callFake( () => {
store = {};
});
TestBed.configureTestingModule({
imports: [],
providers: [
InterceptHttpService,
{ provide: CookieService, useValue: mockCookieService }
InterceptHttpService
]
});
......@@ -46,10 +44,10 @@ describe('InterceptHttpService', () => {
it('should be get right token and send right request when the cookie not exists', inject([InterceptHttpService],
(service: InterceptHttpService) => {
mockCookieService.set("fdsa|ds");
localStorage.setItem("__csrf", mockedCSRFToken);
service.intercept(mockRequest, mockHandle).subscribe(res => {
if (res.status === 403) {
expect(mockRequest.headers.get("X-Harbor-CSRF-Token")).toEqual(cookie);
expect(mockRequest.headers.get("X-Harbor-CSRF-Token")).toEqual(mockedCSRFToken);
} else {
expect(res.status).toEqual(200);
}
......
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { CookieService } from 'ngx-cookie';
import { catchError, tap } from 'rxjs/operators';
const SAFE_METHODS: string[] = ["GET", "HEAD", "OPTIONS", "TRACE"];
@Injectable({
providedIn: 'root'
})
export class InterceptHttpService implements HttpInterceptor {
constructor(private cookie: CookieService) { }
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
return next.handle(request).pipe(catchError(error => {
if (error.status === 403) {
let Xsrftoken = this.cookie.get("__csrf");
if (Xsrftoken && !request.headers.has('X-Harbor-CSRF-Token')) {
request = request.clone({ headers: request.headers.set('X-Harbor-CSRF-Token', Xsrftoken) });
return next.handle(request);
}
// Get the csrf token from localstorage
const token = localStorage.getItem("__csrf");
if (token) {
// Clone the request and replace the original headers with
// cloned headers, updated with the csrf token.
// not for requests using safe methods
if (request.method && SAFE_METHODS.indexOf(request.method.toUpperCase()) === -1) {
request = request.clone({
headers: request.headers.set('X-Harbor-CSRF-Token', token)
});
}
return throwError(error);
}));
}
return next.handle(request).pipe(
tap(response => {
if (response && response instanceof HttpResponse && response.headers) {
const responseToken: string = response.headers.get('X-Harbor-CSRF-Token');
if (responseToken) {
localStorage.setItem("__csrf", responseToken);
}
}
},
error => {
if (error && error.headers) {
const responseToken: string = error.headers.get('X-Harbor-CSRF-Token');
if (responseToken) {
localStorage.setItem("__csrf", responseToken);
}
}
}))
.pipe(
catchError(error => {
if (error.status === 403) {
const csrfToken = localStorage.getItem("__csrf");
if (csrfToken) {
request = request.clone({ headers: request.headers.set('X-Harbor-CSRF-Token', csrfToken)});
return next.handle(request);
}
}
return throwError(error);
}));
}
}
......@@ -36,10 +36,6 @@ export function GeneralTranslatorLoader(http: HttpClient, config: IServiceConfig
imports: [
CommonModule,
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: '__csrf',
headerName: 'X-Harbor-CSRF-Token'
}),
FormsModule,
ReactiveFormsModule,
ClipboardModule,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment