Angular Digest Authentication - angularjs

I'm trying to connect to a RESTFul API on a home automation server in my house (so massive security not required). When I try to connect with no credentials, I get:
[Error] XMLHttpRequest cannot load http://localhost:8176/devices/. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
The documentation says:
Indigo uses "digest authentificaction" (not basic nor token)
curl -X PUT --digest -u {username}:{password} -d value={value} http://{IPAddress}:8176/variables/{VariableToChange}
curl -X PUT --digest -u admin:p#ssw0rd -d value=true http://{IPAddress}:8176/variables/Var1
To get a list of devices, I can use one of these 3:
http://127.0.0.1:8176/devices/
http://127.0.0.1:8176/devices.xml/
http://127.0.0.1:8176/devices.txt/
I'm at a total loss on how to pass the creeds. Here's my code so far:
function DeviceController($scope, $http) {
$http.get("http://localhost:8176/devices/")
.then(function (results) {
//Success;
console.log("Succss: " + results.status);
$scope.devices = results.data;
}, function (results) {
//error
console.log("Error: " + results.data + "; "
+ results.status);
$scope.error = results.data;
})
};
Can anyone point me in right direction?
Thanks
Mark

Your server has to be configured to accept CORS (Cross-origin resource sharing).
EDIT:
It looks like your Indigo (don't know what it is) server is not the one serving your angular app. Please refer to your server's documentation on how to enable CORS.
As far as passing your credentials during your request, do:
$http({
method: "GET",
url: "http://localhost:8176/devices/",
headers: {"Authorization": "Basic " + btoa("admin:p#ssw0rd")},
})...

Related

My code fails for https with bad request and works for http

I have tried everything available on line but in vain. The code below works for http and not https.
I have tls 1.2 enable on my system and ssl certificate is self signed that I am using with https and using IIS web server from MS.
Also when I try to access the url from IIS Browse Website I see the same error with these details:
This error (HTTP 400 Bad Request) means that Internet Explorer was able to connect to the web server, but the webpage could not be found because of a problem with the address.
But there are no issues with the address.
I also see this error in the event viewer:
The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID
{2593F8B9-4EAF-457C-B68A-50F6B8EA6B54}
and APPID
{15C20B67-12E7-4BB6-92BB-7AFF07997402}
to the user CORP\qahee SID (S-1-5-21-606747145-1993962763-839522115-104115) from address LocalHost (Using LRPC) running in the application container Unavailable SID (Unavailable). This security permission can be modified using the Component Services administrative tool.
Though I have changed the permission to full control in the registry for the user CORP\qahee and have rebooted the system before trying again I still get the error.
I have all three version of tls enabled in the registry and also in the internet options.
I wonder if the issue is due to self signed certificate.
Here is my code:
private string GetSessionId(string id)
{
var url
System.Configuration.ConfigurationManager.AppSettings["SessionServerURL"] ??"http://localhost";
System.Net.ServicePointManager.SecurityProtocol |=
System.Net.SecurityProtocolType.Tls12 |
System.Net.SecurityProtocolType.Tls11 |
System.Net.SecurityProtocolType.Tls;
using (var handler = new HttpClientHandler() { UseDefaultCredentials =
true })
{
handler.ServerCertificateCustomValidationCallback =
ServerCertificateCustomValidation;
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
newMediaTypeWithQualityHeaderValue("application/json"));
logger.Debug("handler: " + handler + " url: " + url +
" BaseAddress: " + client.BaseAddress);
// HTTP GET
try
{
HttpResponseMessage response =
client.GetAsync("/System/StartSession/" + id).Result;
logger.Debug("response status: " +
response.StatusCode +
" req msg: " + response.RequestMessage +
" reasonphrase:+response.ReasonPhrase);
if (response.IsSuccessStatusCode)
{
var jsonText =
response.Content.ReadAsStringAsync().Result;
var result =
JsonConvert.DeserializeObject<string>(jsonText);
return result;
}
}
This is the output for http when it runs w/o failure:
response status: OK req msg: Method: GET, RequestUri: 'http://localhost:83/System/StartSession/434f52505c7161686565', Version: 1.1, Content: , Headers:
{
Accept: application/json
} reason phrase: OK
For https this is the failure I get
response status: BadRequest req msg: Method: GET, RequestUri: 'https://abe-s19-qe1.qae.xxx.com:444/System/StartSession/434f52505c7161686565', Version: 1.1, Content: , Headers:
{
Accept: application/json
} reason phrase: Bad Request

how to fix '403 (Forbidden)' on a $http.get request to etherpad

[header][1]
[header][2]
i am trying to send a get request to etherpad hosted in a different domain. the OPTIONS preflight request goes through but the get request returns 403 status.
however when i install CORS for chrome extension the request goes through
when i install cors chrome extension the request goes through
here is my code:
/* ........ export draft to html/pdf/word ........ */
//get content for this template
var url = Drafting.domain + Drafting.port + '/p/' + Drafting.padID + '/export/html?' + 'apikey=' + Drafting.apikey;
$http.get(url).then(function(response, status){
if(typeof(callback)==='function' && callback)
{
callback(response.data);
}
});
```}
[1]: https://i.stack.imgur.com/25dsj.png
[2]: https://i.stack.imgur.com/ivHnn.png
i just passed 'withCredentials:true' together with the url and then modified the importexport.js inside the etherpad files where 'AccessControlAllowOrigin' was set to '*' i replaced it with a specific domain and it worked.

Angular $http.post returns 404 error

I am using angular JS to send some data to Payment Gateway.
Syntax for curl to send data as per documentation is:
curl https://www.mybank.co.uk/3dsecure
-H "Content-type: application/x-www-form-urlencoded"
-X POST
-d 'TermUrl=https://www.yourmerchantsite.co.uk/3DSecureConfirmation&PaReq=value-of-oneTime3DsToken&MD=merchantdatavalue'
However when I am doing it in Angular :
$http({
method: 'POST',
url: 'url',
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html'
},
data: $.param({TermUrl: obj.TermUrl ,Pareq: obj.Pareq }),
})
I am getting error
Possibly unhandled rejection: {"data":"<html><head><title>400 Bad
Request</title></head><body><h1>Bad Request</h1></body>
</html>","status":400,"config":
{"method":"POST","transformRequest":[null],"transformResponse":
[null],"jsonpCallbackParam":"callback","url":"payement gatway
url","headers":{"Content-Type":"application/x-www-form-urlencoded",
"Accept":"text/html,application/xhtml+xml"},"data":"TermUrl=url&Pare
q=value"},"statusText":"Bad Request","xhrStatus":"complete"}
Kindly suggest how to proceed with this one ?
First of all, you are experiencing a 400 Bad Request (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400) and not a 404 Not Found.
It usually means that you are not sending the right data to the server and the API is expecting some specific parameters (from the body usually).
Check the API, look at every parameter required from it - their types and how they should be sent (body param? query string? etc...).
You can use your browser network tab or tools like Postman to see what you are actually sending to the server and if it matches what the server is expecting you to send.
Check out 3D Secure's API reference, you should get back a detailed error code beside the http status code:
https://developer.paysafe.com/en/3d-secure/api/#/introduction/error-summary/common-errors
It should be easily debuggable.

Google drive api invalid client

I am trying to get access to the google drive content of my users.
I can redeem a code on my domain using the google drive user consent url with correct parameters:
https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id='+$scope.googledriveApi.client_id+'&scope='+$scope.googledriveApi.scopes+'&redirect_uri='+$scope.googledriveApi.redirect_uri
I am trying to do an angular $http request to the https://www.googleapis.com/oauth2/v4/token endpoint.
The request looks like this:
$http({
method: 'POST',
headers: {"Content-Type" : "application/x-www-form-urlencoded"},
data: $.param({
"code" : $routeParams.code,
"client_id" : $scope.googledriveApi.client_id,
"client_secret" : $scope.googledriveApi.secret,
"redirect_uri" : $scope.googledriveApi.redirect_uri,
"grant_type" : "authorization_code"
}),
url: 'https://www.googleapis.com/oauth2/v4/token'
})
However the response I get from the request is as follows:
{
"error": "invalid_client",
"error_description": "The OAuth client was not found."
}
Does anyone know why this happens? I have tried changing product name and client id name to be the same. I have checked this for spaces. The reason I'm mentioning this is because this seemed to be the case for other people who asked a question for the same error, however my error happens at the $http request.
I am getting back the user consent code and I am trying to exchange for an access token in this request. This is when the error comes in and I am stuck.
Try these:
Under OAuth consent screen, make sure Product name is not the same with project name as stated in this SO thread:
Try to include an authorization header in your URI request:
headers: { 'Authorization': 'bearer ' + accessToken }

NetworkError: 405 Method Not Allowed AngularJS REST

In AngularJS, I had the following function, which worked fine:
$http.get( "fruits.json" ).success( $scope.handleLoaded );
Now I would like to change this from a file to a url (that returns json using some sweet Laravel 4):
$http.get( "http://localhost/fruitapp/fruits").success( $scope.handleLoaded );
The error I get is:
"NetworkError: 405 Method Not Allowed - http://localhost/fruitapp/fruits"
What's the problem? Is it because fruit.json was "local" and localhost is not?
From w3:
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource
identified by the Request-URI. The response MUST include an Allow header
containing a list of valid methods for the requested resource.
It means the for the URL: http://localhost/fruitapp/fruits The server is responding that the GET method isn't allowed. Is it a POST or PUT?
The angular js version you are using would be <= 1.2.9.
If Yes, try this.
return $http({
url: 'http://localhost/fruitapp/fruits',
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
I had a similar issue with my SpringBoot project, I was getting the same error in the browser console but I saw a different error message when I looked at the back-end log, It was throwing this error: "org.springframework.web.HttpRequestMethodNotSupportedException, message=Request method 'DELETE' not supported " It turned out that I was missing the {id} parameter in the back-end controller:
** Wrong code :**
#RequestMapping(value="books",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
** Correct code :**
#RequestMapping(value="books/{id}",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
For me, it was the server not being configured for CORS.
Here is how I did it on Azure: CORS enabling on Azure
I hope something similar works with your server, too.
I also found a proposal how to configure CORS on the web.config, but no guarantee: configure CORS in the web.config. In general, there is a preflight request to your server, and if you did a cross-origin request (that is from another url than your server has), you need to allow all origins on your server (Access-Control-Allow-Origin *).

Resources