Cannot authenticate $http with passport Basic Auth - angularjs

How can I make my $http call with passport basic auth?
I setup basic auth with passport on my server, and I can use POSTMAN to test. But when I try to do it on my angular application I cannot get it to pass the username and password for the basic auth.
I have the following on my $http call
$http({
method:'POST',
url: 'http://myapicall.com/api/login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization' : 'Basic Username:MySecret'
},....
Do I need to add anything else? I keep getting not authorized and when I use the same username and password on postman it works fine.

Use btoa function to convert your username:password to base64
$http({
method:'POST',
url: 'http://myapicall.com/api/login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization' : 'Basic ' + window.btoa('Username:MySecret')
},....
Or use this library https://github.com/dankogai/js-base64

Related

Can't send auth headers with axios

Can't send authorization header with rest API. Got 'OPTIONS' error with status 0. All headers and options are allowed on the server. Server is written on PHP.
Here is my request:
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData},{
headers:{ 'Content-Type':'multipart/form-data',
Authorization:`Bearer ${token}`}
})
It seems like it does not send the header when there is authorization. However, it works, if i delete authorization, and leave only content type
This should do the trick
axios({
method: 'POST',
url:`${API_URL}users/${23}/profile/main/update`,
headers: {
'Content-Type':'multipart/form-data',
'Authorization':`Bearer ${token}`},
data: formData
})
Refer docs for browser
Try to send as below:
var headers = {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData}, headers)
Try using Ajax call below:
import $ from 'jquery';
$.ajax({
url:`${API_URL}users/${23}/profile/main/update`,
processData: false,
contentType: false,
data : formData,
method : "POST",
headers: {
"Authorization": `Bearer ${token}`
}
});
I had this same issue, it is possible that you are not passing the sent auth header from your apache config to your php application.
you might need to set
WSGIPassAuthorization On
inside your virtualhost config.
Check this

Url Encoding in AngularJS front end with Spring REST backend

quick question. I have an AngularJS front end communicating with a Spring REST backend . URL encoding is only necessary for encoding parameters passed in the url (for application/x-www-form-urlencoded). I don't have to worry about the encoding in the body, correct ?
For content type of application/x-www-form-urlencoded the body of a post message needs to be uri encoded:
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
OR alternately:
var config = {
transformRequest: $httpParamSerializer,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
$http.post(myUrl, myData, config);
For more information, see:
AngularJS $httpParamSerializer Service API Reference
AngularJS $httpParamSerializerJQLike Service API Reference

jhipster oauth : How can i get the token via CURL

I am trying to use the jhipster to create a new project with the oauth2 authentication. The project example works fine, I can login with the angularjs interface. However when I try to retrieve an access_token using CURL in the command line, I get response as :
"error":"Unauthorized","message":"Bad credentials"
Can someone help me on how to use curl to get the access_token?
Here you go!
curl http://127.0.0.1:8080/oauth/token --request POST --insecure --data
"username=[xxx]&password=[yyy]&grant_type=password&scope=read%20write&
client_secret=[your app secret]&client_id=[your app id] " -H
"Authorization:Basic [base64 of your appid:appsecrt]"
uncomment cors in application.yml inside jhipster
cors: #By default CORS are not enabled. Uncomment to enable.
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
To access REST API with Oauth2 authentication in ionic you must first get the token in ionic app by
$http({
method: "post",
url: "http://192.168.0.4:8085/[Your app name]/oauth/token",
data: "username=admin&password=admin&grant_type=password&scope=read write&client_secret=my-secret-token-to-change-in-production&client_id=auth2Sconnectapp",
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Basic ' + 'YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24='
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});
here "YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24=" is equal to (clientId + ":" + clientSecret)--all base64-encoded
you can use https://www.base64encode.org/ to verify or recreate it for yourself
the aboue $http if successful will give you this JSON which contains token and it's expiry time
{
"access_token": "2ce14f67-e91b-411e-89fa-8169e11a1c04",
"token_type": "bearer",
"refresh_token": "37baee3c-f4fe-4340-8997-8d7849821d00",
"expires_in": 525,
"scope": "read write"
}
take notice of "access_token" and "token_type" if you want to access any API this is what you have to use. We send the token with API to access data until the token expires then we either refresh it or access for a new one.
for example
$http({
method: "get",
url: "http://192.168.0.4:8085/auth-2-sconnect/api/countries",
withCredentials: true,
headers: {
'Authorization':' [token_type] + [space] + [access_token] '
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});
A simple way to do it:
Just open FireBug in Firefox browser, simulate the login process with the right credentials
Locate the login request in the "NET" tab.
Right-click on it then click on "Copy as cURL"
Paste the copied value in the terminal to see what is expected to be in your cURL request: it looks verbose but you can omit certain
parameters. The required parameters are mentioned in #Rajender Saini answer
up there.
All is done.

AngularJs $http.post -> Error: Unexpected Request POST ; no more request expected

I've got a working curl request here:
curl -u testclient:testpass http://mybackend.somedomain.com/token.php -d 'grant_type=client_credentials'
Now I try to translate this to my angularJs (ionicframework) frontend.
(The php-backend is on a different server, so this might maybe have something to do with CORS, too, though I don't know how)
In my frontend I try:
var username = 'testclient';
var password = 'testpass';
var url = 'http://mybackend.somedomain.com/token.php';
var request = $http({
method: "post",
url: url,
data: {
username: username,
password: password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
This results in something weird, the POST request isn't executed, but instead I get the error message:
Error: Unexpected request: POST http://mybackend.somedomain.com/token.php No more request expected
What am I doing wrong here ?
There is a mistake in your Angular POST, your data is encoded as JSON instead of what you claim in headers application/x-www-form-urlencoded. First you should change your code to below.
$http({
method: 'POST',
url: url,
data: $.param({
username: username,
password: password
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})

Angular JS - $http not sending headers

As the title suggest, I need to pass an authorization token but when I check the network console, I'm getting a 403 because the accept and authorization isn't there. NOTE: I removed my authorization token for this example
$http({
url: 'http://api.stubhub.com/search/catalog/events/v2?title="san"',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": 'application/json',
"Authorization": 'Bearer {token}'
}
}).success(function(response){
$scope.searchResponse = response;
}).error(function(error){
$scope.error = error;
});
This seems like correct syntax? What's wrong here?
EDIT: added the XHR screenshot
EDIT: 2. Here's my network traffic, HAR via paste bin:
http://pastebin.com/fiFngZSy
setting custom headers on XHR requests triggers a preflight request.
I bet you're seeing an OPTIONS request without the Authorization header, and a corresponding response whose Access-Control-Allow-Headers header value is not listing Authorization, or the API doesn't even allow unauthorized OPTIONS requests.
I don't know the stubhub api, but does it return CORS-compliant responses?

Resources