Ionic 3 - Http Get 401 (Unauthorized) - http

I’m calling a service using a token
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Http failure response for http://localhost:65291/api/post: 401 Unauthorized
The same call works in Postman with Headers;
Content-Type: application/json
Authorization: Bearer token
The function in ionic is
getPosts() {
var header = new HttpHeaders({ "Content-Type": "application/json" });
header.append("Authorization", "Bearer " + this.token);
console.log("Bearer " + this.token);
return new Promise(resolve => {
console.log(this.apiUrl + '/post');
this.http.get(this.apiUrl + '/post', { headers: header}).subscribe((data: Post[]) => {
resolve(data);
}, err => {
console.log(err);
});
});
}
Added a log for the token to be sure that is adding it to the header correctly (the token is fine).
The apiUrl variable has value http://localhost:65291/api.
What is wrong here? Cors is enabled… Postman works ok…
Thanks

I think you definitely have client side problem (since its 401 and also you mention Postman works ok).
I had similar issues when I tried to append headers in the same fashion you did so I would suggest trying this (to eliminate this problem):
getPosts() {
// try forming headers object in one go:
let token = "Bearer "+this.token
let headers = new HttpHeaders({
"Content-Type": "application/json",
"Authorization": token
});
// now here I am not sure why you do promise wrapping this way, but then I would suggest:
return this.http.get(this.apiUrl + '/post', { headers: headers })
.toPromise()
.then((data: Post[]) => { // Success
console.log(data);
resolve(data);
}, (err) => {
console.log(err);
});
}
If the problem is still there - please share which version of Angular and Http module you are using?
Also check out this issue here: How to correctly set Http Request Header in Angular 2
And specifically this answer if you are on Angular 4.3+:
How to correctly set Http Request Header in Angular 2

After a while I found the problem,
header.append("Authorization", "Bearer " + this.token); is wrong. It worked using
let headers = new HttpHeaders({"Authorization: " + "Bearer " + this.token})
Setting multiple headers:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()

I had a similar problem, it works on postman and cors enabled but in the app doesn't work, my problem was i have / at the end of the URL in the API security config, and i was making the request without /, i just remove it from request URL,
also you can add /* in security config or put / in your app, the URL must be the same.
(maybe you have solved your issue and it was different issue but this is a possibe solution)

Related

Google Firebase Messaging API facing CORS error

Hi there Guys i'm tryng to subscribe Firebase Cloud Messaging channels with provided token via capacitor/ioni app using PWA. But i got a CORS issue when i publish the www folder, instead on localhost it is working
This is the code im using in .ts file
this.devices = response;
FirebaseMessaging.requestPermissions().then(result => {
if(result.receive === 'granted')
{
FirebaseMessaging.getToken(
{
vapidKey: 'my-vapid-key',
}
).then( result => {
const token = result.token;
this.devices.forEach(i => {
let topic = i.serial
fetch('https://iid.googleapis.com/iid/v1/'+ token +'/rel/topics/'+ topic, {
method: 'POST',
headers: new Headers({
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
'Authorization': 'key=my-key'
})
}).then(response => {
alert('Fatto')
if (response.status < 200 || response.status >= 400) {
throw 'Error subscribing to topic: '+response.status + ' - ' + response.text();
}
console.log('Subscribed to "'+topic+'"');
}).catch(error => {
console.error(error);
})
})
this.addReceivedListener();
the error i faced is: "https://iid.googleapis.com/iid/v1/xxxxxxxxtokeeeen/rel/topics/mytopic' from origin 'https://mysite.site.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
there is no CORS on the other side, so we need to disable it and its working

LinkedIn returns 401 REST API when making request with HttpClient

I am unable to retrieve the profile details when making a call the /people endpoint.
using(HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.TempToken);
client.DefaultRequestHeaders.Add("x-li-format", "json");
var response = await client.GetAsync("https://api.linkedin.com/v1/people/~?format=json");
if (response.IsSuccessStatusCode)
{
return "success";
}
return "failed";
}
I can confirm that the token is coming through at this point. And I have just successfully authorized before I pass the token to this code block.
Below is my request message:
{Method: GET, RequestUri: 'https://api.linkedin.com/v1/people/~?format=json', Version: 1.1, Content: , Headers:
{
Authorization: Bearer AQTgH0PIdKoSnCbbDaFhubm2q3wJcmv-qvxOqcd42qbdzfDja4DUj5Cs0YMk6RZ37Gv_0WWsrv24C9vhOG7d8M3IlPS9fez9DjwNu37U71PLiTzGPN-I4j1FsY7aJeMmf9I1v_XXXXXXXXXXXXXXXXX_3ADwlS6_a9
x-li-format: json
x-ms-request-root-id: 388de07b-44400de197c25bd0
x-ms-request-id: |388de07b-44400de197c25bd0.1.
Request-Id: |388de07b-44400de197c25bd0.1.
}}
Any assistance would be greatly appreciated.
Thanks
I was having the same issue for a few hours on 21-June. Fortunately it resolved itself so I'm assuming a linkedin api problem.

How to get custom response header in angular 2?

I am new to angular 2 and currently working with angular 2.2.1 in which I am successfully able to post request and get success response however when I try to get Authorization header from response I always get null whether I am able to get Content-Type header. Below is my solution so far.
service.ts login method:
login(model: LoginModel) {
let requestUrl = '/someurl';
let requestPayload = JSON.stringify(model);
let headers = this.getHeaders(false); // ... Set all required headers
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(requestUrl, requestPayload, options) // ...using post request
//.map((res: Response)) // ...and calling .json() on the response to return data
.subscribe((res: Response) => {
var payload = res.json();
var authorization = res.headers.get('Authorization');
var contentType = res.headers.get('Content-Type');
console.log(payload, contentType, authorization)
});
}
Header Helper
getHeaders(isSecureAPI: boolean) {
let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
if (isSecureAPI) {
headers.append('Authorization', 'GetFromSession');
headers.append('X-UserID', 'GetFromSession');
}
return headers;
}
Fiddler track:
Angular Console Output
So anyone can guide me what I am possibly doing wrong?
Header was allowed but not exposed on CORS server however adding headers.add("Access-Control-Expose-Headers", "Authorization, X-Custom"); on server did the job :)
I've been trying to find a solution and came across this
Let's say I'm using the Microsoft Cors WebAPI 2 Nuget package, and I have the following global configuration in my WebApiConfig.cs:
...
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
...
The EnableCorsAttribute constructor accepts a 4th string parameter to globally allow any additional headers:
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*", "X-Foo, X-Bar, X-Baz");

How to read received headers in Angular 2?

Can some body tell me how to read received headers in Angular 2?
i have mad a request, for login and password, and there should be sent back headers with Token. I need the token for further workaround.
here is part of the code:
sendLogin(username, password) {
let body = JSON.stringify({"username": username, "password": password});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.loginUrl, body, options)
.map(res => res.json())
.map((res) => {
if (res.ok) {
// at least how to console.log received headers?
console.log( res.headers); //undefined
this.loggedIn = res.ok;
} return res.ok;
});
};
thank you.
Most of the time such an issue is related to CORS. You need to explicitly enable allowed headers in the response headers.
You're only be able to see the header in the map only if it's enabled by CORS.
Your server needs to return the following in headers:
Access-Control-Allow-Headers: X-SomeHeader

Http REST call problems No 'Access-Control-Allow-Origin' on POST

I have not been able to get Angular $http to communicate with a remote REST service. I have tried Restangular and $resource too. The problem seems to be with the underlying $http service and CORS limitations. I think I just need to get my headers right. Do I also need to tweak my server config?
I am getting the following error:
XMLHttpRequest cannot load http://www.EXAMPLE-DOMAIN.com/api/v2/users/sign_in. No 'Access-Control- Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
I have researched this a lot. Currently I have tried setting the $httpProvider headings when configuring my app module and played with $http headers. Below is some of my current code.
My Service
app.service('Auth', function($http) {
var headers = {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
return $http({
method: "POST",
headers: headers,
url: 'http://www.EXAMPLE-DOMAINcom/api/v2/users/sign_in',
data: {"email":"my#email.com","password":"secret"}
}).success(function(result) {
console.log("Auth.signin.success!")
console.log(result);
}).error(function(data, status, headers, config) {
console.log("Auth.signin.error!")
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
});
App Config
var app = angular.module('starter', ['ionic', 'app.controllers', $httpProvider])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
If you are in control of the server, you might need to set the required headers there. Depending on which server, this might help: http://enable-cors.org/server.html

Resources