angular 5 send request header and receive response header using HttpClient - angular5

I have written an authentication service in Angular 5 which does a GET request to my backend using the HttpClient class.
My request looks like this:
headers = new HttpHeaders().set('Content-Type', 'application/json')
.set('X-XSRF-TOKEN', 'sdfhjsdgh');
const options = ({ headers: headers});
this.http.get('http://127.0.0.1:8080/api/v1/display', options)
.filter(data => data.status === 200 || data.status === 206)
.map((res) => this.success(res))
.catch((res) => this.failure(res, service));
How do I access the authorization header of the response?
Any help is very much appreciated.

Related

How to mock the same request of different origins URLs (for TestCafe)

I need to mock the same request, that is initiated by 2 different origins (url1, url2).
But the only one request (from 1st origin url1) is mocked.
How to work with multiple origins?
Thanks in advance.
const urlRegExp = new RegExp('/events');
const mock = RequestMock()
.onRequestTo(urlRegExp)
.respond({eenter code hererror: 'this request has been mocked'}, 500, {
'access-control-allow-origin': 'url1.com',
'access-control-allow-credentials': true
})
.onRequestTo(urlRegExp)
.respond({error: 'this request has been mocked'}, 500, {
'access-control-allow-origin': 'url2.com',
'access-control-allow-credentials': true
});
You need to modify your onRequestTo calls. Please take a look at the Filter With Predicate section of TestCafe documentation.
const mock = RequestMock()
.onRequestTo(request => {
return request.url === 'http://example.com' &&
request.method === 'post' &&
request.isAjax &&
request.body.toString() === 'foo=bar';
})
.respond(/*...*/);
You can set your request mock to filter requests by request headers such as host, referer, origin, etc. Thus you need to write different filters for your different requests.

POST Fetch request returns: grant_type was not specified

I had working code for fetching a access token with oauth, then I did a expo eject and now when I try to POST my auth code to get the access_token i receive response.
.then((auth_code) => {
let my_headers = new Headers()
my_headers.append('Authorization', `Basic ${base64_auth}`)
my_headers.append('Content-Type', 'application/x-www-form-urlencoded')
my_headers.append('Access-Control-Allow-Origin', '*')
my_headers.append('grant_type', 'authorization_code')
let urlencoded = new URLSearchParams()
urlencoded.append('code', auth_code)
urlencoded.append('grant_type', 'authorization_code') // <-- GRANT_TYPE HERE
let request_options = {
method: 'POST',
headers: my_headers,
body: urlencoded,
mode: 'cors'
}
console.log(request_options) // <--- OUTPUT BELOW
let url_with_params = `https://${url}/oauth/token/`
fetch(url_with_params, request_options)
.then((response) => response.json())
.then((json) => console.log(json)) // <--- OUTPUT BELOW
.then((json) => helpers.set_session_object('oauth_object', json))
.finally(() => set_loading(false))
.catch((error) => console.log('error', error))
})
.catch((error) => console.error(error))
console.log(request_options) outputs the following:
{method: "POST", headers: Headers, body: URLSearchParams, mode: "cors"}
body: URLSearchParams {_searchParams: Array(1)}
headers: Headers
map:
access-control-allow-origin: "*"
authorization: "Basic YXdheTprTkwpUmtWc2lWM2ppaCk3WDlmZXp3aSk="
content-type: "application/x-www-form-urlencoded"
grant_type: "authorization_code"
method: "POST"
mode: "cors"
and the json response outputs:
{"error": "invalid_request", "error_description": "The grant type was not specified in the request"}
Any idea why this is happening? I obviously have the grant_type declared right?
Looking at this I can see a couple of things that may not be quite right:
Remove the trailing backslash at the end of the OAuth token URL
Include a redirect_uri field, which is required in Authorization Code Grant messages
I suspect the first issue above is causing a redirect so that the POST to https://url/oauth/token/ becomes a GET to https://url/oauth/token.
Some similar issues are described in this post, and above all else I would aim to ensure that you can use an HTTP Proxy tool to view messages, which will make you much more productive at diagnosing this type of issue in future.
PROXY MOBILE SETUP
If it helps, my blog has some posts on proxy setup details:
Android HTTP Proxy Setup
iOS HTTP Proxy Setup

Http with token in Ionic 4

(Sorry for my bad english) I have to access an api, with a token that they have provided me. My problem is that I don't know how to implement it, after searching and searching, it gives me the following error:
Access to XMLHttpRequest at 'https://www.presupuestoabierto.gob.ar/api/v1/credito' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I pass my code to you, to indicate that it is wrong in the definition of the token (the x instead of the token) and eventually in the CORS policy, thank you very much!
const headers = { 'Authorization': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8100'}
this.http.get<any>('https://www.presupuestoabierto.gob.ar/api/v1/credito', { headers }).subscribe(data => {
this.datos = data.blabla;
})
Headers should pass like this in Ionic- Angular. Make sure that you have a service file.Visit this link to know more about services:
https://angular.io/tutorial/toh-pt4
let headers = new Headers({
'Content-Type' : 'application/json',
'Auth':authvalue
});
return this.http.get(url,options).pipe(map(res => res.json()));

How to send an additional request to endpoint after each test case

I’m currently looking at Botium Box, and I’m wondering if it is possible to send an additional request to our endpoint after each test case? Let me give you some background information about how we set up the HTTP(S)/JSON connector in Botium Box and how we are sending information to our bot:
HTTP(S) endpoint:
https://MyChatBotsEndpoint.com/?userinput={{msg.messageText}}
HTTP method: POST
We also send cookies through the header template in the request builder. Like this:
{
"Cookie": "JSESSIONID={{context.sessionId}}"
}
The response is given back in JSON.
When a test ends (when it is successful but also when it fails), we need to send an additional request to our endpoint. The endpoint URL of that request should look like this:
https://MyChatBotsEndpoint.com/endsession
The header should include the cookie as described before.
Is there a way to achieve this in Botium?
Botium has many extension points to plug in your custom functionality. In this case, I guess the SIMPLEREST_STOP_HOOK is the best choice.
Write a small javascript file calling your endpoint, and register is with the SIMPLEREST_STOP_HOOK capability in botium.json. The context (session context from the HTTP/JSON connector) is part of the hook arguments.
in botium.json:
...
"SIMPLEREST_STOP_HOOK": "my-stop-hook.js"
...
my-stop-hook.js:
const request = require('request')
module.exports = ({ context }) => {
return new Promise((resolve, reject) => {
request({
method: 'GET',
uri: 'https://MyChatBotsEndpoint.com/endsession',
headers: {
Cookie: "JSESSIONID=" + context.sessionId
}
}, (err) => {
if (err) reject(err)
else resolve()
})
})
}

React native fetching data from secured API's endpoint with JWT

I'm developing React Native application which is connected to Web API written in ASP.NET Core 2.1. I'm trying to make GET request to my secured API's endpoint, but it doesn't work both with fetch and axios.
Noteworthy is fact, when I make request to unsecured (marked as AllowAnonymous) endpoint, everything works fine.
I'm passing following header 'Authorization' : 'Bearer ' + MY_TOKEN
When I tried to use axios, then it returned HTTP 401. When using fetch it returns HTTP 500.
const url = `${baseUrl}/api/cars/get`
fetch(url, {
headers: new Headers({
Authorization: "Bearer <MY_TOKEN_HERE>"
}), method: "GET"
})
I'm sure the token is valid because I am able to get data from API with Postman and with .NET Core console application client.
Is there any way to get the data from secured API's endpoint?
I solved the issue with just one line of code.
axios.defaults.headers.common['Authorization'] = `Bearer ${TOKEN}`
Then I am able to invoke the get request.
const url = `${baseUrl}/api/values`;
axios.get(url)
.then(data => {
console.log(data);
})
.catch(error => {
})
Hope it helps someone who will have such issue in the future.