I am trying to call an API in AngularJS. API has HTTP Basic Authentication with username = admin and password = admin123
This is how I am calling the API,
$http.get('https://example.com', {
headers: {'Authorization': 'Basic YWRtaW46YWRtaW4xMjM='}
}).then(console.log("something"));
But, it is giving me 401 UnAuthorized response. What is the recommended way to pass the username and password ? I am using AngularJS 1.
Error is showing,
OPTIONS https://example.com 401 ()
Failed to load https://example.com: Response for preflight has invalid HTTP status code 401.
Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"Authorization":"Basic YWRtaW46YWRtaW4xMjM=","Accept":"application/json, text/plain, */*"},"url":"https://example.com"},"statusText":"","xhrStatus":"error"}
You're probably going to want to set the authorization headers at a more global level if all of your requests are going to need it. You can do this by adding
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = '<Basic Auth Header>';
}]);
In your app config. To answer your actual question, I don't see anything specifically wrong with the code that you provided. Could you provide some information around what the server side is expecting and how it's reading the authorization?
Related
I'm trying to make authorized requests to LinkedIn's API after using OAuth2.0 to sign in users. I keep getting errors regarding the CORS policy and need help in sending the correct headers so that I no longer get these errors.
I've tried including a couple different 'Access-Control-Request' headers but I keep getting the same error. I'm pretty sure it has something to do with the 'Authorization' header I'm sending to the API, but this header is required from the documentation to receive the correct information.
https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/context#step-1-configure-your-application
The code I'm using to make this call is shown below...
async function getProfileData(accessToken, expiresIn) {
const requestUrl = `https://api.linkedin.com/v2/me`;
const response = await fetch(requestUrl, {
method: 'GET',
headers: {
'Host': 'api.linkedin.com',
'Connection': 'Keep-Alive',
'Authorization': `Bearer ${accessToken}`,
'Origin': REDIRECT_URI,
'Access-Control-Request-Method': 'GET',
'Access-Control-Request-Headers': 'Content-Type, Authorization'
}
});
return response;
}
The accessToken, in this case, comes from a previous network call using an authorization code from a previous step. Everything before this is working and I'm getting a response with what I assume to be a valid access token.
Previously, I was getting an error saying that my access token wasn't valid even though I followed the documentation step-by-step to retrieve it. I'm not sure if this is the same issue or not, but I can't see a reason why I would have an invalid token (the token wasn't expired and I never rejected the permissions on sign-in).
The response I'm expecting to get back from the call is the basic profile data from the user that is signed in but instead, I get this:
OPTIONS https://api.linkedin.com/v2/me 401
getProfileData # app.js:74
(anonymous) # app.js:50
Access to fetch at 'https://api.linkedin.com/v2/me' from origin 'https://simple-linkedin-login2.netlify.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I am developing a web app with angular.js v1.5.7, which integrates Box Services using oauth2 authentication on the client-side to retrive the tokens for accessing the API.
I have a problem when the access token expires. I make a request with the expired token, and I receive a 401 (unauthorized) response that I can't catch in Angular because the response has a status code of -1. This happens before I am able to catch this response in a $httpsInterceptor.
I made a repository in GitHub to demonstrate this behavior https://github.com/danyfu/box-api-test, it's an express server that serves the 3000 port the Angular app.
In the Angular app, it's only a button you click to request to the API to GET the root folder of the user:
https://api.box.com/2.0/folders/0?fields=id,name,type,item_status,size,item_collection,shared_link
With the request I add the access token.
When I make the request with the invalid token, the response returns two error logs.
Errors
When I make the request with a valid access token, it retrieves the folder info and a status of 200.
Correct Information
You can use passport-box which will do the oauth flow in your app.
https://github.com/bluedge/passport-box
Here's an example where I use it as well:
https://github.com/kendomen/boxadmin
I have an angular JS application, from where I am calling a GET API. The API is OAuth 2.0 enabled, so requires a Bearer Token in the header. So, I am calling the http method like this:
var config = {
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': "Bearer XXXXXXX"
}
};
$http.get("http://host:port/api_call", config)
.then(function (response) {
return response.data;
});
But when I am making this call, I am getting 401 Unauthorized exception. Initially I thought of this as a CORS issue, So I whitelisted the origin to make call to the services host, but still didn't work. So, I checked the logs and found that Authorization header is not coming to the API application, though angular is sending the same.
Note: Is this the best way to make a service call from Angular?
I am quite new to Angular JS and thus have almost no idea how to diagnose or troubleshoot this type of issues. Can someone please tell me the possible errors/how to troubleshoot this?
The issue was in the API gateway. It was not able to make Cross Origin Calls and thus the API call was terminated there, hence Authorization header was not coming.
EDIT: So I changed my code so that I'm handling the base64 encoding myself, which as one user noted, might be necessary.
Now I've encountered a new problem. I'm getting a CORS preflight error that looks like this:
Fetch API cannot load http://flightxml.flightaware.com/json/FlightXML2/FlightInfo. Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Correct me if I'm mistaken: This would imply that the server does not allow "authorization" headers within HTTP requests (which doesn't make any sense, seeing as the docs explicitly tell me to encode the username and API key and pass them as an auth header).
I saw some other posts about this issue, but since I did not build the server, I can't go in and make the change that allows auth headers.
Any new ideas? Thank you so, so much!
ORIGINAL POST:
I'm building a React app that integrates with the FlightAware API.
I made a FlightAware component for handling HTTP requests to the API. I want to start with a simple request to get information about a given plane flight. Unfortunately, I keep getting a 401 unauthorized response despite providing my credentials via state.
(I know this isn't best practices, I'm just doing it temporarily to get the request working.)
Any idea what I'm doing wrong here? Here's the code for the request:
componentDidMount() {
var form = new FormData();
form.append('ident', this.state.flightnum);
form.append('howMany', '10');
form.append('offset', '0');
fetch('http://flightxml.flightaware.com/json/FlightXML2/FlightInfo', {
method: 'GET',
auth: {
user: this.state.user,
pass: this.state.key
},
data: form
})
.then(result => {
// do something...
});
}
I'm trying to learn paypal payment. I have done a simple AngularJS application that use Paypal-Express-Checkout. As it says on the documentation, first of all I have to do the call SetExpressCheckout.
$http.post("https://api-3t.sandbox.paypal.com/nvp", request)
.success(function(data){
console.log(data);
}).error(function(error){
console.log(error);
});
In the object request there are all payment details.
But when I run the script, the result of http call is: XMLHttpRequest cannot load https://api-3t.sandbox.paypal.com/nvp. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I tried to search this error, but I find nothing. How can I solve?
UPDATE: If the request comes from a form does not give me any error but if it come from http.post function it give me an error
You have to perform your Paypal transaction on the back end, and the message you're seeing is Paypal enforcing that notion. See this article on CORS for more info.
Your angular http call should be sending the basic transaction info to your server, which will then construct an API request for Paypal, handle the response from Paypal, and then convey that information for consumption by the client side.
[edited to add more info about CORS]