401 Unauthorized in ionic - angularjs

I am developing a app in Ionic framework.The api calls data from secured server.When i check the api in browser i am getting this popup.
So i could not use this api in mobile app.i found some solution for this issue nothing worked Here is the code i have tried
var string = username + ":" + password;
// Encode the String
var encodedString = btoa(string);
$http({method: 'GET', url: 'https://creatorup.com/wp-json/users/me',
headers: { 'Authorization': 'Basic ' + encodedString }
})
When i use this code i got the response "401 (unauthorized)" error.

Related

Getting Spotify Token w fetch fails on Android but works on iOS - using Expo

This is my code trying to get a token from the Spotify API, the "code" value in "dataToSend" is from authentication which works fine, but then I get [Unhandled promise rejection: TypeError: Network request failed] after the POST request (fetch) executes.
try{
var dataToSend = {
code: code,
redirect_uri: makeRedirectUri(),
grant_type: 'authorization_code'};
//making data to send on server
var formBody = [];
for (var key in dataToSend) {
var encodedKey = encodeURIComponent(key);
var encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
//POST request
var response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST', //Request Type
body: formBody, //post body
headers: {
//Header Defination
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')),
},
})
console.log(response.status, "RESPONSE")
return await response.json()
}catch (error){
console.log(error,error.toString(),"code: " + code)
return error.toString()
}
I tried logging the response status to look for an https code but since this whole thing is inside a try-catch block the code exits before even reaching the console.log. Because of that I'm thinking the issue is something else other than just a bad request because otherwise the fetch request would still go through and the code would continue past the console.log line (I think?).
This same code works on iOS but not Android. I tried running the app on localhost, LAN, Tunnel, and the published version as well (expo published) in case it's something funky with that but nothing seems to work.

How to pass bearer token in $window.open url

I am opening the url without authentication using below code,
$window.open(downloadUrl);
I want to use below authorization
Authorization': 'Bearer ' + '123hrwertjwtjwjrtr',
i have used below code but it is not working,
var params =
{
'Authorization': 'Bearer ' + '123hrwertjwtjwjrtr',
'Content-type': 'application/x-www-form-urlencoded',
};
var downloadUrl = somedummyurl;
var url = [downloadUrl, $.param(params)].join('?');
$window.open(url);
Can anyone suggest how to add bearer token while calling the api url.
In api am using httpget method and used authorize tag..

Symfony + AngularJS 401 unauthorized error after Get method

I have some concerns(marigolds) with my method GET when I send my request. I have received an error 401 and I am disconnected from the application, knowing that the token which I obtain in the console is very valid when I test on postman. I does not really understand(include) why that does not work I have to add some things or I have pain make something.
var list = function(){
var mytoken = window.localStorage.getItem('token');
return $http({
method : 'GET',
url : apiEndpoint.url + '/list',
withCredentials : true,
headers : {Authorization : 'Bearer ' + mytoken}
}).then(function(res) {
console.log(res.data);
});
};
If somebody could me helped please, thank you :)
I think that she uses of the angularJS in her project, while RequestOptions is a class which we find that in Angular 2. That's why the import does not work
It must be added in the conf of apache:
SetEnvIf Authorization. + HTTP_AUTHORIZATION = $ 0
It should work for your case :)
Please check it like below:
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + YourToken);
let options = new RequestOptions({ headers: headers });
this.http.get('YourUrl', options)
This should work

Auth0 NodeJS Authentification Refused using npm request

I'm facing a problem, I tried to connect to Auth0 API to enable a strong identification on my WebApp.
For context :
Front-End : I'm using an angularJS front, and there I implemented the Lock Library to manage the Auth0 popup by following this webapp-specific tutorial.
Back-End : NodeJS & Express server, in order to verify the user's authentification, I use the npm lib "request" to call the Auth0 API.
If i understand well, a click on the auth0 widget sends a request to the specified endpoint URL, and it's received by the back-end:
app.get('/auth0CallbackURL', function (req, res) {
console.log(req.query.code);
var auth0code = req.query.code;
var client_secret = PROCESS.ENV.SERCRETID;
var domain = PROCESS.ENV.DOMAIN;
var client_id = PROCESS.ENV.CLIENTID;
var redirectUrl = PROCESS.ENV.REDIRECTURL;
var request = require('request'); // request-promise
var requestParams = {
url: 'https://mycompanydomain.auth0.com/oauth/token?client_id='+client_id+'&redirect_uri='+redirectUrl+'&client_secret='+client_secret+'&code='+auth0code+'&grant_type=authorization_code',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
And then I call request() to get back the access_token and verify the authentification.
request(requestParams, function(err, data) {
if (err) {
console.log('Err:', err);
} else {
console.log('response body: ', data.body)
}
But the only result I get is :
{
"error": "access_denied"
"error_description": "Unauthorized"
}
At the begining i thougt it was my Auth0 configuration that's didn't allow my authentification, but it seems that there are OK.
Thanks in advance for your replies.
As per the page you linked, you need to pass the following information:
client_id=YOUR_CLIENT_ID
&redirect_uri=https://YOUR_APP/callback
&client_secret=YOUR_CLIENT_SECRET
&code=AUTHORIZATION_CODE
&grant_type=authorization_code
in the request body and with a content type of application/x-www-form-urlencoded.
You're setting the content type correctly, but then are passing the data in the URL query component and instead you need to pass it the POST request body.
Using request package you should do the following:
var requestParams = {
url: 'https://mycompanydomain.auth0.com/oauth/token',
method: 'POST',
body: 'client_id=' + client_id +
'&redirect_uri=' + redirectUrl +
'&client_secret=' + client_secret +
'&code=' + auth0code +
'&grant_type=authorization_code',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}

How to remove basic authentication in angularness?

Hi am using basic authentication for webservie integration.
$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode(Username + ':' + password);
$http({method: 'GET', url: 'http:url.com'}).
success(function(data) {
if(data=='' || data==null || data=='undefined'){
var alertPopup = $ionicPopup.alert({
title: 'Info!',
template: 'Invalid Password, or no user found with this Email Address'
});
alertPopup.then(function(res) {
console.log('Invalid Password, or no user found with this Email Address ');
});
}
This code is working fine for me .but my problem is if one user is logedin using username and password.then logged out after that another user try to logged in with different username and password will get the previous user loged in. how to clear the header authentication data?
You could probably redefine the header with
$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode(newUsername + ':' + newPassword)
It seems that,
You have not replaced the Authorization header when
the user logged out
logged in as a different user
Login - call this every time a user logs in
function setCredentials(username, password) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode(username + ':' + password);
};
Logout - call this when a user logs out
function clearCredentials() {
$http.defaults.headers.common.Authorization = 'Basic ';
};
The above snippets simplified from this tutorial - AngularJS Basic HTTP Authentication Example. i recommend reading it
In addition,
Please note that using basic http authentication is insecure because the password passed on each request with no encryption!
As an alternative, you can change basic http authentication to a server side authentication using sessions (comment the server your'e using and i'll link you to example)
If you still decides to keep the basic http authentication, at least use HTTPS !
I've found this solution working:
When initiating a logout, first try making a bad request with a fake user to throw away the currently cached credentials.
I have this function doing the requests (it's using jquery's $.ajax with disabled asynch calls):
function authenticateUser(username, hash) {
var result = false;
var encoded = btoa(username + ':' + hash);
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Basic ' + encoded);
},
url: "user/current",
statusCode: {
401: function () {
result = false;
},
200: function (response) {
result = response;
}
},
async: false
});
return result;
}
So when I try to log a user out, this happens:
//This will send a request with a non-existant user.
//The purpose is to overwrite the cached data with something else
accountServices.authenticateUser('logout','logout');
//Since setting headers.common.Authorization = '' will still send some
//kind of auth data, I've redefined the headers.common object to get
//rid of the Authorization property
$http.defaults.headers.common = {Accept: "application/json, text/plain, */*"};

Resources