Access jhipster Oauth2 authenticated REST API in ionic app - angularjs

While accessing jhipster Oauth2 API in my ionic app but I am getting no response. This is the $http request I am sending from my ionic app
$http({
method: "post",
url: "http://192.168.0.5:8080/auth-2-sconnect/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: {
'Accept':'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});
it also gives **Status Code:403 Forbidden** error if I insert
'Authorization': 'Basic ' + 'YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24='
inside headers

I un-commented CORS in application.yml of jhipster application, that seems to do the trick.
My ionic application is working fine now.

Related

CORS post call not working in Angularjs

I am trying to implement cross-origin post call from angularjs application, then I get the following error.
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
But, when I make a Ajax call it works properly.
How HTTP post call work in angularjs?
Ajax call
$.ajax({
type: 'POST',
url: getAccessTokenUrl,
data: JSON.stringify(clintdata),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resultData) {
console.log(resultData);
},
error: function (request, status, error) {
console.log(status);
}
});
Angularjs HTTP call
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
'Authorization': undefined,
'Auth-Token': undefined
}
}).then(function(res){
console.log(res);
}, function(err){
console.log(err);
});
I have some default setting. Authorization is for others REST
$http.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8;' ;
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Access-Control-* headers are response headers. They come from the server in response to a request. You do not apply them to your request headers.
If your jQuery request works correctly without adding any additional headers, then your AngularJS request should work the same.
The equivalent jQuery request in AngularJS (including removing the Authorization and Auth-Token headers you've set via defaults) is
$http.post(getAccessTokenUrl, clientdata, {
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(response => {
console.log(response.data)
})
or the long version
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(...)
AngularJS by default...
POSTS requests as application/json content-type
Serializes the data property to JSON
Expects a JSON response
Resolves the $http promise with a response object with the response body parsed as JSON into the data property
Remove the following setting
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Add Authorization header dynamically from Interceptor
request: function(config) {
if (angular.isUndefined(config.skipInterceptor) || !config.skipInterceptor) {
// add Authorization token
}
return config;
}
Http call like this
$http.post('your url', {
skipInterceptor: true
})

Mailchimp api not working with fetch and Reactjs

I cannot get the fetch api to work with the mailchimp api in React. I'm also using webpack to run a devserver.
This is what I have:
componentDidMount() {
let authenticationString = btoa('123:myapikey-us17');
authenticationString = "Basic " + authenticationString;
fetch('https://us17.api.mailchimp.com/3.0/lists/fakelistid/segments', {
mode: 'no-cors',
method: 'GET',
credentials: 'same-origin',
headers: new Headers({
'Authorization': authenticationString,
'Accept': 'application/json',
'Content-Type': 'application/json'
})
}).then(function(e){
console.log("fetch finished")
}).catch(function(e){
console.log("fetch error");
})
}
I've tested the exact same api request in Postman and that works fine.
When I try this in React I keep getting a 401 status code saying "Your request did not include an API key."

How to handle CORS requests in AngularJS

I'm facing problem with CORS requests in AngularJS while calling web services but the same service able to call by using jQuery.
Note: From server side we are receiving header "Access-Control-Allow-Origin:*" and these services are running fine in jQuery application.
Here I'm posting my AngularJS code as well as jQuery code.
AngularJS:
$http({
method: 'POST',
url: $rootScope.host + "UserLogin",
//headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
"uname": $scope.uname,
"password": $scope.password
},
}).then(function (success) {
$scope.loginDetails = success;
console.log($scope.loginDetails);
}),function (error){
console.log(error);
});
If I pass the header like headers: { 'Content-Type': 'application/x-www-form-urlencoded' } able to ping the service but my request is not going in JSON format.
If I change the header to 'Content-Type': 'application/json', getting
XMLHttpRequest cannot load https://XXXX.XXXX.in/XXXXAPI/UserLogin.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://170.11.0.61' is therefore not allowed access.
I don't know what is the reason for this error.
$.ajax({
url: BASE_URL + "UserLogin",
type: "POST",
xhrFields: {withCredentials: true},
data: {
"uname": uname,
"password": password
},
cache: false,
success: function (result, textStatus, request) {
console.log(result);
},
error: function (e) {
console.log("Error in login service call:"+JSON.stringify(e));
}
});
This jQuery is sending my request in the json format.
Try to pass headers like
headers: { 'Content-Type': 'application/json' }

Cannot authenticate $http with passport Basic Auth

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

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.

Resources