Aurelia - Setting headers in Aurelia Fetch Client - javascript

I'm using aurelia-http-client and struggling to both use interceptors and set headers for my requests.
What I need to achieve is;
Each Interceptor (request, request error, response, and response error) emits an event using aurelia-event-aggregator when it's triggered.
A header is added to each request containing information entered on the page
The only way I've got interceptors to correctly publish events is to use aurelia.container in main.js like below;
import {HttpClient} from 'aurelia-http-client';
import {EventAggregator} from 'aurelia-event-aggregator';
export function configure(aurelia) {
const container = aurelia.container;
const httpClient = container.get(HttpClient);
const ea = container.get(EventAggregator);
httpClient.configure(config => {
config.withInterceptor({
request(request) {
ea.publish('http-request', request);
return request;
},
requestError(error) {
ea.publish('http-request-error', error);
throw error;
},
response(response) {
ea.publish('http-response', response);
return response;
},
responseError(error) {
ea.publish('http-response-error', error);
throw error;
}
});
});
aurelia.use
.standardConfiguration()
.developmentLogging()
.singleton(HttpClient, httpClient);
aurelia.start().then(() => aurelia.setRoot());
}
Because the header for my request must be set after the App has initialised - I can't do it in the configuration above like most tutorials online do.
Instead, it needs to be set as below;
import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
import {EventAggregator} from "aurelia-event-aggregator";
#inject(HttpClient, EventAggregator)
export class Dashboard {
requestMethod = "GET";
constructor(HttpClient, EventAggregator) {
this.http = HttpClient;
this.ea = EventAggregator;
}
triggerGet() {
// HEADER NEEDS TO BE SET HERE USING THIS.FOO
this.http.get(this.url).then(response => {
console.log("GET Response", response);
});
}
}
I've tried variations of;
this.http.configure((configure) => {
if(this.username && this.password) {
configure.withDefaults({
headers: {
'Authorization': 'Basic ' + btoa(this.username + ":" + this.password)
}
});
}
})
But I can't get anything to alter the header where I need to, and maintain the configuration I've set up in main.js

Fabio Luiz in the comments set me on to a working solution. It's not ideal I don't think, but it works.
I've essentially created an AppState class that I use to pass the username/password to the interceptor;
export class AppState {
properties = {};
clear() {
this.properties = {};
}
set(key, value) {
this.properties[key] = value;
}
get(key) {
if(this.properties[key]) {
return this.properties[key];
} else {
return false;
}
}
}
It's pretty rough and ready, but it's only for a test Application so I'm happy with it.
Here's its use;
import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
import {EventAggregator} from "aurelia-event-aggregator";
import {AppState} from "services/appState";
#inject(HttpClient, EventAggregator, AppState)
export class Dashboard {
constructor(HttpClient, EventAggregator, AppState) {
this.http = HttpClient;
this.ea = EventAggregator;
this.appState = AppState;
// Create listeners
}
run() {
if(this.username && this.password) {
this.appState.set('authenticate', true);
this.appState.set('username', this.username);
this.appState.set('password', this.password);
}
// Trigger HTTP Requests
}
}
Then my main.js file;
import {HttpClient} from 'aurelia-http-client';
import {EventAggregator} from 'aurelia-event-aggregator';
import {AppState} from 'services/appState';
export function configure(aurelia) {
const container = aurelia.container;
const httpClient = container.get(HttpClient);
const ea = container.get(EventAggregator);
const appState = container.get(AppState);
httpClient.configure(config => {
config.withInterceptor({
request(request) {
if(appState.get('authenticate')) {
let username = appState.get('username');
let password = appState.get('password');
request.headers.add("Authorization", "Basic " + btoa(username + ":" + password));
}
ea.publish('http-request', request);
return request;
},
requestError(error) {
ea.publish('http-request-error', error);
throw error;
},
response(response) {
ea.publish('http-response', response);
return response;
},
responseError(error) {
ea.publish('http-response-error', error);
throw error;
}
});
});
aurelia.use
.standardConfiguration()
.developmentLogging()
.singleton(HttpClient, httpClient);
aurelia.start().then(() => aurelia.setRoot());
}

Try creating an actual headers object like this:
this.http.configure((configure) => {
if(this.username && this.password) {
configure.withDefaults({
headers: new Headers({
'Authorization': 'Basic ' + btoa(this.username + ":" + this.password)
})
});
}
})

Related

Django + React Axios instance header conflict?

I have all my functions based views on django protected with #permission_classes([IsAuthenticated]) so I have to send a JWT as Bearer token on every request.
In the first version I was using this code:
import axios from 'axios';
import { decodeUserJWT } from '../../extras'
const user = JSON.parse(localStorage.getItem("user"));
var decoded = decodeUserJWT(user.access);
var user_id = decoded.user_id
const instance = axios.create({
baseURL: 'http://localhost:8000/api',
headers: {Authorization: 'Bearer ' + user.access},
params: {userAuth: user_id}
});
export default instance;
Everything was working fine.
But then I added interceptors so I could handle the refreshToken process:
const setup = (store) => {
axiosInstance.interceptors.request.use(
(config) => {
const token = TokenService.getLocalAccessToken();
if (token) {
// const uid = await decodeUserJWT(token);
config.headers["Authorization"] = 'Bearer ' + token;
// config.headers["userAuth"] = uid;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
const { dispatch } = store;
axiosInstance.interceptors.response.use(
(res) => {
return res;
},
async (err) => {
const originalConfig = err.config;
if (originalConfig.url !== "/auth/token/obtain/" && err.response) {
console.log("TOKEN INTERCEPTOR");
// Access Token was expired
if (err.response.status === 401 && !originalConfig._retry) {
originalConfig._retry = true;
try {
const rs = await axiosInstance.post("/auth/token/refresh/", {
refresh: TokenService.getLocalRefreshToken(),
});
const { access } = rs.data;
dispatch(refreshToken(access));
TokenService.updateLocalAccessToken(access);
return axiosInstance(originalConfig);
} catch (_error) {
return Promise.reject(_error);
}
}
}
return Promise.reject(err);
}
);
};
What happens?
When I add the line config.headers["userAuth"] = uid; the django server console starts showing up that when the react app tries to access the routes it gets a Not Authorized, and when I take that line off de code ... it works fine.
I also tried to pass the param userAuth in the axios.create and keep only the Bearer config inside the interpector code, but still no positive result, the code with the interpector code only works when I take off the userAuth line from axios.
Any ideia on why this is happening and how can I fix this?

Axios / JWT post 401 (Mac OS and iOS only) "rest_forbidden"

I'm working on a Vue app that uses Axios and Wordpress JWT Auth for authentication. Recently I started getting this 401 when trying to post (100% of the time) ...but... only on Mac OS X and iOS.
Can you point me in the right direction as to how to troubleshoot this? The error object in Chrome console network is this:
{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":401}}
My post looks like this:
https://wordpressroot.ourdomain.com/wp-json/jwt-auth/v1/folder/transfer {location_id: "rec4ttKVWJCDr8v", items: Array(1)}
axios localClient:
import axios from "axios";
import environment from "#/environments/environment";
import state from "../store";
import router from "../router";
const userData = JSON.parse(localStorage.getItem("userData"));
let instance = {};
if (userData) {
instance = axios.create({
baseURL: environment.CUSTOM_BASE_URL,
headers: { Authorization: `Bearer ${userData.token}` }
});
} else {
instance = axios.create({
baseURL: environment.CUSTOM_BASE_URL
});
}
instance.interceptors.request.use(
config => {
state.commit("setNetworkStatus", true);
return config;
},
error => {
return Promise.reject(error);
}
);
instance.interceptors.response.use(
response => {
state.commit("setNetworkStatus", false);
return response;
},
error => {
if ([401, 403].includes(error.response.status)) {
console.log(error);
state.commit("delUserData");
router.push("/login");
}
return Promise.reject(error);
}
);
export default {
get(path) {
return instance.get(instance.defaults.baseURL + path);
},
post(path, params) {
console.log(instance.defaults.baseURL + path, params);
return instance.post(instance.defaults.baseURL + path, params);
},
put(path, params) {
return instance.put(instance.defaults.baseURL + path, params);
},
delete(path, params) {
return instance.delete(instance.defaults.baseURL + path, params);
}
};

Nested Observables behaving differently in Ionic2/Angular2 App

I am creating an ionic login module, where in there are 2 observables , 1 inside another, Not sure if this is the correct way of implementation,
Here I am trying to call getHTTP() method, get a string, if the string is not empty then set it in ionic-storage varaible and then verify before logging in
Since Observables are async - getHTTP() is getting completed after the flow of login(credentials) , Help me out
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import {Headers} from '#angular/http';
import { Response } from '#angular/http';
import { Storage } from '#ionic/storage';
export class User {
name: string;
password: string;
url: string;
constructor(name: string, password: string, url: string) {
this.name = name;
this.password = password;
this.url = url;
}
}
/*
Generated class for the AuthService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class AuthService {
currentUser: User;
data = '';
constructor(public http: Http,private storage: Storage) {
console.log('Hello AuthService Provider');
}
// Make a call to Get CSRF and check if we have access
public getHTTP(credentials) {
let responseCSRF ;
const headers: Headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa(credentials.user + ':' + credentials.password));
headers.append('Content-Type', 'application/json');
console.log(headers);
console.log('Clearing cache');
this.storage.set('CSRF', '');
this.storage.set('Auth',btoa(credentials.user + ':' + credentials.password));
this.storage.set('url', credentials.url);
//return
responseCSRF = this.http.get('http://' + credentials.url +'/Windchill/servlet/rest/security/csrf', {
headers: headers
}).map((response: Response) => response.json());
//console.log(typeof(responseCSRF))
responseCSRF.subscribe(x => {
console.log('CSRF ->' + x.items[0].attributes.nonce)
this.data = x.items[0].attributes.nonce;
if(typeof this.data!='undefined' && this.data) {
this.storage.set('CSRF', this.data);
}
});
return responseCSRF;
}
public login(credentials) {
if (credentials.user === null || credentials.password === null || credentials.url === null ) {
return Observable.throw("Please insert credentials ");
} else {
return Observable.create(observer => {
// At this point make a request to your backend to make a real check!
let access = false;
this.getHTTP(credentials).subscribe (
(resBody) => console.log('Boby is '+resBody),
error => console.error('Error from auth-service: ' + error))
, () => console.log('Completed!' + 'Auth' );
this.storage.get('CSRF').then((val) => {
console.log('Your CSRF is'+ val);
if(val!='undefined') {
access = true;
}
});
observer.next(access);
observer.complete();
});
}
}
public getUserInfo() : User {
return this.currentUser;
}
public logout() {
return Observable.create(observer => {
this.currentUser = null;
observer.next(true);
observer.complete();
});
}
}
In the Console
Headers {_headers: Map(2), _normalizedNames: Map(2)}
auth-service.ts:49 Clearing cache
auth-service.ts:57 pluck -->[object Object]
auth-service.ts:83 Your CSRF is
auth-service.ts:59 CSRF ->RkPYp+UtGGMRB+8NJHCr9rJ6WhBHdIVCfim585xXKgZ1TKUmf3v39tBqVRkjSb93dgWi4oF3KF4rNts0c3frktUdIFokNNVrMSGM47V3KwQhP8A5ARKr5rBsaxtmOtI=
auth-service.ts:78 Boby is [object Object]
Try to put your storage.get logic inside subscription handler:
return Observable.create(observer => {
// At this point make a request to your backend to make a real check!
let access = false;
this.getHTTP(credentials).subscribe(
(resBody) => {
console.log('Boby is ' + resBody);
this.storage.get('CSRF').then((val) => {
console.log('Your CSRF is' + val);
if (val != 'undefined') {
access = true;
}
observer.next(access);
observer.complete();
});
},
error => console.error('Error from auth-service: ' + error),
() => console.log('Completed!' + 'Auth'));
});

Angular2: oauth2 with token headers

I'm new to angular2. In 1.* everything was fine with interceptors, just add them: and you have everywhere your headers, and you can handle your requests, when token became invalid...
In angular2 i'm using RxJs.
So i get my token:
getToken(login: string, pwd: string): Observable<boolean> {
let bodyParams = {
grant_type: 'password',
client_id: 'admin',
scope: AppConst.CLIENT_SCOPE,
username: login,
password: pwd
};
let params = new URLSearchParams();
for (let key in bodyParams) {
params.set(key, bodyParams[key])
}
let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({headers: headers});
return this.http.post(AppConst.IDENTITY_BASE_URI + '/connect/token', params.toString(), options)
.map((response: Response) => {
let data = response.json();
if (data) {
this.data = data;
localStorage.setItem('auth', JSON.stringify({
access_token: data.access_token,
refresh_token: data.refresh_token
}));
return true;
} else {
return false;
}
});
}
and then how can i use this token in every request? i don't want to set .header in every request. It's a bad practice.
And then: for example when i do any request, and get 401-error, how can i intercept, and get a new token, and then resume all requests, like it was in angular 1?
i tried to use JWT from here jwt, but it doesn't meet my requirements, btw in first angular i was using Restangular - and everything was fine there (also with manual on tokens:https://github.com/mgonto/restangular#seterrorinterceptor)
You can either extend the default http service and use the extended version, or you could create a method that gets some parameters (if necessary) and return a RequestOptions objects to pass default http service.
Option 1
You can create a service:
#Injectable()
export class HttpUtils {
constructor(private _cookieService: CookieService) { }
public optionsWithAuth(method: RequestMethod, searchParams?: URLSearchParams): RequestOptionsArgs {
let headers = new Headers();
let token = 'fancyToken';
if (token) {
headers.append('Auth', token);
}
return this.options(method, searchParams, headers);
}
public options(method: RequestMethod, searchParams?: URLSearchParams, header?: Headers): RequestOptionsArgs {
let headers = header || new Headers();
if (!headers.has('Content-Type')) {
headers.append('Content-Type', 'application/json');
}
let options = new RequestOptions({headers: headers});
if (method === RequestMethod.Get || method === RequestMethod.Delete) {
options.body = '';
}
if (searchParams) {
options.params = searchParams;
}
return options;
}
public handleError(error: Response) {
return (res: Response) => {
if (res.status === 401) {
// do something
}
return Observable.throw(res);
};
}
}
Usage example:
this._http
.get('/api/customers', this._httpUtils.optionsWithAuth(RequestMethod.Get))
.map(res => <Customer[]>res.json())
.catch(err => this._httpUtils.handleError(err));
This example is using cookies to store and access the token. You could use a parameter as well.
Option 2
Second option is to extend http service, for example like this:
import { Injectable } from '#angular/core';
import { Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class MyHttp extends Http {
constructor (backend: XHRBackend, options: RequestOptions) {
let token = 'fancyToken';
options.headers.set('Auth', token);
super(backend, options);
}
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let token = 'fancyToken';
if (typeof url === 'string') {
if (!options) {
options = {headers: new Headers()};
}
options.headers.append('Auth', token);
} else {
url.headers.append('Auth', token);
}
return super.request(url, options).catch(this.handleError(this));
}
private handleError (self: MyHttp) {
return (res: Response) => {
if (res.status === 401) {
// do something
}
return Observable.throw(res);
};
}
}
And in your #NgModule:
#NgModule({
// other stuff ...
providers: [
{
provide: MyHttp,
useFactory: (backend: XHRBackend, options: RequestOptions) => {
return new MyHttp(backend, options);
},
deps: [XHRBackend, RequestOptions]
}
]
// a little bit more other stuff ...
})
Usage:
#Injectable()
class CustomerService {
constructor(private _http: MyHttp) {
}
query(): Observable<Customer[]> {
return this._http
.get('/api/customers')
.map(res => <Customer[]>res.json())
.catch(err => console.log('error', err));
}
}
Extra:
If you want to use refresh token to obtain a new token you can do something like this:
private handleError (self: MyHttp, url?: string|Request, options?: RequestOptionsArgs) {
return (res: Response) => {
if (res.status === 401 || res.status === 403) {
let refreshToken:string = 'fancyRefreshToken';
let body:any = JSON.stringify({refreshToken: refreshToken});
return super.post('/api/token/refresh', body)
.map(res => {
// set new token
})
.catch(err => Observable.throw(err))
.subscribe(res => this.request(url, options), err => Observable.throw(err));
}
return Observable.throw(res);
};
}
To be honest, I haven't tested this, but it could provide you at least a starting point.
We solved the issue with extension of AuthHttp. We added a method a on AuthHttp to set a new header dynamically like that (X-RoleId is a custom header)
declare module 'angular2-jwt' {
interface AuthHttp {
setRoleId(config: {});
}
}
AuthHttp.prototype.setRoleId = function (roleId) {
let jsThis = <any>(this);
jsThis.config.globalHeaders = [
{'Content-Type': 'application/json'},
{'X-RoleId': roleId}
];
};

Value become null for this in Promise callback

I am using the following code value of this become null when i call it inside the then function here is the code. Am i doing something wrong or it is like this or there is any work around to resolve this issue
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { CanActivate, Router } from '#angular/router';
import { AuthService } from '../services/auth.service';
import { WebAPISettings } from '../services/webapisettings.service';
#Injectable()
export class LoginService {
//_ngWEBAPISettings: WebAPISettings;
//_authService: AuthService;
constructor(private http: Http, private ngWEBAPISettings: WebAPISettings, private authService: AuthService) {
//this._ngWEBAPISettings = ngWEBAPISettings;
//this._authService = authService;
}
public login(username: string, password: string): Promise<any> {
let data = "grant_type=password&username=" + username + "&password=" + password;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
try {
debugger;
return this.http.post(this.ngWEBAPISettings.apiServiceBaseUri + "token", data, options)
.toPromise()
.then(function (res: Response) {
debugger;
let body = res.json();
//let _authService: AuthService = new AuthService();
this.authService.fillAuthDataFromLogin(body);
//this.router.navigate(['/Home']);
return body.data || {};
})
.catch(this.handleError);
}
catch (error) {
console.log(error);
}
}
private extractData() {
}
private handleError(error: any) {
debugger;
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
and i am debugging it in the chrome here is the screenshot please help me in fixing it.
after using the arrow function same thing check the screen shot
one thing to mention i am using Angular2 RC4.
You could use an arrow function to be able to use the lexical this:
return this.http.post(this.ngWEBAPISettings.apiServiceBaseUri + "token", data, options)
.toPromise()
.then((res: Response) => { // <-----
(...)
});
This way, this will correspond to the instance of the LoginService service.
See this doc for more details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Categories

Resources