How do I setup Basic Auth for the Fetch API? - fetch

So I have a referer and Basic Auth that I need to send a Get Request, no body is needed. I am sending out the function like this, but I am getting a Failed to Fetch Error
fetch(myUrl, {
method: 'GET', // or 'PUT'
headers: {
'Referer': refererUrl,
},
authorization: {
'Authorization': 'Basic ' + btoa(authUser + ":" + authPassword),
}
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});

Referer is one of the headers that cannot be set by a client, for security reasons:
https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name

Related

Unable to make API call from react native app in local machine

I'm running my app on android emulator on my mac and trying to hit a service endpoint which is deployed on firebase. I'm getting 500 error saying nothing and when I'm trying to print the error it says There was a problem sending log messages to your development environment [PrettyFormatPluginError: value.hasOwnProperty is not a function. (In 'value.hasOwnProperty('tag')', 'value.hasOwnProperty' is undefined)].
When I try to hit the same endpoint using postman and the same payload, I'm succesfully able to do it.
Following code is written in the app
fetch('https://{app_url}.cloudfunctions.net/app/user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: userPayload
})
.then(response => response.text())
.then(result => {
console.log('User in DB created');
console.log(result);
})
.catch(error => console.log('error', error));
Can anyone help me here ?
You're setting Accept: 'application/json', so you should change ".then(response => response.text())" to ".then(response => response.json())". Let me know if it works.
fetch('https://{app_url}.cloudfunctions.net/app/user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: userPayload
})
.then(response => response.json())
.then(result => {
console.log('User in DB created');
console.log(result);
})
.catch(error => console.log('error', error));

React Native - How to get private posts from WordPress REST API using JWT Token

I have done logging-in WordPress Rest API with JWT Plugin passing administrator account and password and stores the received token in AsyncStorage like this.
await AsyncStorage.setItem(
'user',
JSON.stringify({
token: userData.token,
user_email: userData.user_email,
user_nicename: userData.user_nicename,
user_display_name: userData.user_display_name,
}),
);
Then I manage to get all posts including private post by including the token with request header like this,
let userInfo = await AsyncStorage.getItem('user');
let jsonUser = await JSON.parse(userInfo);
let credential = 'Bearer ' + jsonUser.token;
fetch('http://localhost/reactnativewordpress/wp-json/wp/v2/posts', {
headers: {
Authorization: credential,
},
method: 'GET',
withCredentials: true,
credentials: 'include',
})
.then(response => response.json())
.then(responseJson => {
this.setState({
items: responseJson
});
})
.catch(error => {
console.log('Error :' + error);
});
The responseJson have only public posts, no private post at all.
Thanks for help.
You need to add the
status=private
in your request,
like this http://localhost:8000/wp-json/wp/v2/posts?status=private
With that, the Authorization header should run ;)

axios firebase refresh token authorization header not override

I'm trying to refresh token(firebase) in react native without success. It add the new token but in this way
Authorization Bearer old_token, Bearer new_token
Expected behaviour
Authorization Bearer new_token
Here is my code, we can see the instance, interceptor for append current token to all request and finally the interceptor for the refresh token. I don't know what I'm missing.
const customConfig: AxiosRequestConfig = {
baseURL: 'http://localhost:3000',
headers: {
'content-type': 'application/json',
},
responseType: 'json',
};
const instance: any = axios.create(
customConfig,
);
// interceptor to put token to all request
instance.interceptors.request.use(
async (config: any) => {
const token = await AsyncStorage.getItem('token');
if (token) {
config.headers.authorization = 'Bearer ' + token;
console.log("config.headers.authorization", config.headers.authorization)
}
return config;
},
(error: any) => {
Promise.reject(error);
},
);
// interceptor to handle refresh token
instance.interceptors.response.use((response: any) => {
return response;
},
function (error: any) {
console.log("error en axios", error)
const originalRequest = error.config;
if (!error.response) {
return Promise.reject('Network Error');
}
if ((error.response.status === 401) && !originalRequest._retry) {
originalRequest._retry = true;
return firebase.auth().currentUser?.getIdTokenResult(false).then((res) => {
AppStorage.setToken(res.token).then(() => { console.log('Token saved'); });
const addToken = 'Bearer ' + res.token;
instance.defaults.headers.common['Authorization'] = addToken;
originalRequest.headers['Authorization'] = addToken;
return axios(originalRequest);
});
}
return Promise.reject(error);
},
);

How do you generate a token for creating a WordPress user in angular 4

Can someone explain:
let header = new Headers({"Authorization": "Bearer "+token});
How should i get that value for the token?
I am using wp-api-angular
here is a code example:
signUpForm() {
const headers = new Headers({
'Authorization': 'Bearer' + this.token
});
this.wpApiUsers.create(
this.newUser,
{ headers: headers })
.toPromise()
.then(response => {
console.log(response);
}
);
}
I now Have This:
signUpForm() {
this.http.post('https://website.com/wp-json/jwt-auth/v1/token', {
username: 'admin',
password: 'password'
}).subscribe(data => {
if (data['token']) { // if token is returned
this.token = data['token'];
const headers = new Headers({
'Authorization': 'Bearer' + this.token
});
const options = new RequestOptions({ headers: headers });
this.http.post(
'https://website.com/wp-json/wp/v2/users',
this.newUser,
options
);
}
});
}
But now I am getting this error:
Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'.
Types of property 'headers' are incompatible.
Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated.
Property 'keys' is missing in type 'Headers'.
const headers: Headers
The token allows you to have authorization to access data that can't be accessed by a non authenticated user, it is generated when you successful sign-in.
You first need to request the token (Sign-in), for that you must do a POST request with the username and password, the response will have the token that you should save and use after for other requests that requires authorization.
this.http.post('http://YOUR_DOMAIN/wp-json/jwt-auth/v1/token', {
username: this.user.login,
password: this.user.password
}).subscribe(
(data) => {
if (data['token']) { // if token is returned
console.log(data['token']); // Token
}
}, (error) => {} // Authentication errors
);
Complete tutorial: https://www.sitepoint.com/angular-wordpress-wp-api-angular/

Ionic 2 - Get token from Storage value and set Header before HTTP Request

I am using the ionic/storage package to store the api_token for users after they logged in so I can use the unique token to interact with an API.
The problem I am facing is that I need to get the value via storage.get which returns a promise and results in the headers I want to set not being set in time.
I need to return an instance of RequestOptions but can't figure out how to add the header I retrieve when it comes from a promise. Adding a header synchronous with localStorage is working fine when testing so the issue must be the asynch execution.
createAuthorizationHeader(headers: Headers) {
// this does add the header in time
localStorage.setItem('api_token', 'some token');
headers.append('Authorization', 'Bearer ' + localStorage.getItem('api_token'));
// this does not add the header in time
return this.storage.get('api_token').then((value) => {
headers.append('Authorization', 'Bearer ' + value);
});
}
getHeaders(path): RequestOptions {
let headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
});
if(!this.isGuestRoute(path)) {
this.createAuthorizationHeader(headers);
}
return new RequestOptions({ headers: headers });
}
get(path: string) {
return this._http.get(this.actionUrl + path, this.getHeaders(path))
.map(res => res.json())
.catch(this.handleError);
}
Edit: Working code now looks like this
getApiToken(): Observable<Headers> {
return Observable.fromPromise(this.storage.get('api_token'));
}
getHeaders(): Headers {
return new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
});
}
get(path: string) {
let headers: Headers = this.getHeaders();
if(!this.isGuestRoute(path)) {
return this.getApiToken().flatMap(data => {
headers.append('Authorization', 'Bearer' + data);
return this._http.get(this.actionUrl + path, { headers : headers })
.map(res => res.json())
.catch(this.handleError);
});
}
return this._http.get(this.actionUrl + path, { headers : headers })
.map(res => res.json())
.catch(this.handleError);
}
Check out my similar problem Angular2 - Use value of Observable returning method in another Observable
If you convert the Promise to a Observable you will be able to use the rxjs flatMap function.
Let me show you what your would somewhat look like then
getApiToken(): Observable<Headers> {
return Observable.fromPromise(this.storage.get('api_token'));
//OR return Observalbe.of(this.storage.get('api_token'));
}
getHeaders(): Headers {
//create all headers here except the 'api_token'
.....
}
get(path: string): Observable<any> {
let headers: Headers = this.getHeaders();
return this.getApiToken().flatMap(data => {
headers.append('Authorization', 'Bearer'+data);
return this.http.get(this.actionUrl + path, headers)
.map(res => res.json())
.catch(this.handleError);
});
}
OR (Just learned about this so not sure if it will work)
createAuthorizationHeader(headers: Headers) {
// this does add the header in time
localStorage.setItem('api_token', 'some token');
headers.append('Authorization', 'Bearer ' + localStorage.getItem('api_token'));
// this does not add the header in time
let api_token = await this.storage.get('api_token');
headers.append('Authorization', 'Bearer ' + api_token);
}
I would suggest looking at Interceptors: https://angular.io/guide/http (serach for the section named "Setting new headers"). I tried using BaseRequestOptions but that still causes an async problem.
Regadring Ivaro18 answer, of setting the headers as the token is received and saved in storage, won't that break when the user returns to an app/page after killing the app/ closing browser? The header are set in memory, so it won't be persistent.

Resources