Angular 4 JWT token shows "401 unauthorized" - javascript

I've seen similar threads to this issue, but I had no luck solving it.
I'm trying to access my .net core controller "GET" using angular post.
getAll() {
return this.http.get('api/Users/GetAll', this.jwt()).map((response: Response) => response.json());
}
I'm getting this error :
401 Unauthorized
jwt code :
private jwt() {
// create authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
if (currentUser && currentUser.token) {
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer ' + currentUser.token)
return new RequestOptions({ headers: headers });
}
}
currentUser.token consist a valid token, I can access it via console.log, etc.
What am I doing wrong?

Related

Not able to call API with Authorization Token in Angular

I am trying to call an API to get current user details and need to attach token with the Authorization header. However it is failing to call API with 500 error response.
It is working absolutely fine from Postman and curl command and I am getting user details.
Code for it as below:
httpHeaders = new HttpHeaders ({
'Content-Type': 'application/json'
});
getCurrentUser(url){
var token = localStorage.getItem('token');
this.httpHeaders = this.httpHeaders.set('Authorization', `Bearer ${localStorage.getItem('token')}`);
return this.http.get<any>(url, { headers: this.httpHeaders });
}
I tried different ways to concatenate token with Bearer prefix however getting Authorization in console as Bearer "token-string" (not sure if this is the reason my API is failing).
public getCurrentUser(url: string): Observable<unknown> {
const token = localStorage.getItem('token');
// Launch DevTools to step through the code in the debugger;
debugger;
// check if token is valid string as well
if (token == null) {
throw new Error('Authorization token not found');
}
// Use local object
const httpHeaders = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
});
return this.http.get<unknown>(url, { headers: httpHeaders });
}
If you still receive HTTP 500 internal server error from server:
Open DevTools and review the error messages in Console or Network tab if any.
Review the server logs if you have access to them.

read CSV coming from rest-api in Angular-8

I have a rest-api which is returning csv file, how can i get it in the angular service.
getCSV() {
let headers_object = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': "Bearer "+ "7woNSuuEYqLfQAuqwHhCJn8aq2SM"
});
const httpOptions = {
headers: headers_object,
Accept: 'text/csv'
};
this._http.get(
'https://00.00.xx.00:9001/abcd/export', httpOptions
).subscribe(resp => {
console.log(resp)
}
);
}
Data is coming in network tab, but angular goes into the ERROR status saying http failure during parsing for because somehow it is expecting the json return.
Please help
Headers in POSTMAN as attached in image.

Fetching data using Angular 5 HttpClient

I am trying to load data from a rest endpoint using the HttpClient provided by Angular. The endpoint in question uses a token to authorize the user.
getData() {
if (this.token) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer' + ' ' + this.token
})
};
this.http.get('https://some url', httpOptions).subscribe((res) => {
console.log(res);
}, (error) => {
console.log(error);
});
} else {
this.empty_token = true;
}
}
I get the following error while trying to do that:
Response for preflight has invalid HTTP status code 401.
However, the same code works for a some demo url that works on "http" and not for "https".
I tried using the same by making a request using Postman or any other RestClient for that matter and it works fine.
If the calling url is http it is normal that it does not work.
This could help you https://angular.io/api/platform-browser/DomSanitizer
Or try this
private httpOptions = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + this.token});
you should add
"proxies": [
{
"path": "/v1",
"proxyUrl": "'https://some url'"
}
to your project .
you can look to this link https://github.com/mgechev/angular-seed/wiki/Add-a-Proxy-to-browsersync

How do I access response headers using HttpClient in Angular 5?

I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. The backend responds by sending a JWT bearer token.
My request looks like this:
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
'username': username,
'password': password
}, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json')
})
.toPromise()
.then(response => {
console.log(response);
return response;
});
}
How do I access the authorization header of the response?
When I write the response to the console, like above, it says 'null'. I know the error is not in the backend because I captured the traffic and the backend is indeed sending the bearer token.
Any help is very much appreciated.
To access the full response (not just the body of the response), you must pass the observe: 'response' parameter option in your http request. Now you can access the headers with res.headers
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
'username': username,
'password': password
}, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json'),
observe: 'response'
})
.map(res => {
let myHeader = res.headers.get('my-header');
});
Docs

Token is not being set while calling API in angular 4

i'm facing the issue that when i set header i'm unable to send the token to the API.one more strange issue is that when i see in my network log, i can see method getting converted to 'OPTION', also my 'Token' is not being sent. see below Error :
i have tried to find out all the ways but nothing worked for me, can anyone help here.
Reffered questions :
Using http rest apis with angular 2
Angular2 OPTIONS method sent when asking for http.GET
My code :
//set token for Authorization
setHeaders() {
var token = this.localStorageService.getToken();
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
headers.append('Authorization', token);
this.options = new RequestOptions({ headers: headers });
}
//function
getMaintenanceType() {
this.setHeaders();
return this.http.get(this.url_Configuration.maintenancetype, this.options)
.map(res => res.json())
}
Please try to use below solution, it will work.
Set Header with the request :
Create a method setHeader :
setHeader(): RequestOptions {
let headers = new Headers()
headers.append('Accept', 'application/json');
headers.append("X-Auth-Token", this.accesToken);
let options = new RequestOptions({ headers: headers });
return options;
}
And then Use it :
this.http.get(this.baseURL + url, this.setHeader()).map(res => res.json());
I see that you are having Error Code 403. By Any chance, is your server running on a different platform like 'apache, JBOSS, ... etc' and your UI application is on different. If that is the case, You need to implement CORS support to your server, and I can help you with it, once you confirm the server environment.
As of now, I see a couple of things that can be changed in your code, for starters, and this might help too:
headers ;
headers = new Headers ({ 'Content-Type': 'application/json' });
this.headers.append('Accept', 'application/json');
this.headers.append("X-Auth-Token", this.accesToken);
let options = new RequestOptions({ headers: headers, method: 'get' });

Categories

Resources