Authentication with Azure using OAuth2 for an ionic mobile app - angularjs

I have been trying to retrieve the token from Azure AD by posting in the username and password using the HTTP angular service. Unfortunately, I always get this error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
It complains the following: "The request body must contain the following parameter: 'grant_type'"
Does anyone have any idea what this is happening?
This is my login controller and I have set up my Azure AD already.
function access() {
var username = vm.username.trim();
var password = vm.password.trim();
requestAccessToken(username, password);
}
function requestAccessToken(username, password){
var base_url = 'https://login.windows.net';
var client_id = "35d16a1c-3f01-402a-9346-ee13b0aa2ba0";
var params = '?grant_type=password&client_id=' + client_id + '&username=' + username + '&password=' + password;
var path = "/4397b89d-d9d7-4d27-9cac-f7ae0ff0d880/oauth2/token";
//var path = "/common/oauth2/token"; we have tried this one too
var url = base_url + path + params;
$http.post(url).success(getAccessTokenSuccess).error(getAccessTokenFailure);
}
function getAccessTokenSuccess(data, status, header, config) {
console.log('data: ', data);
}
function getAccessTokenFailure(data, status, header, config) {
console.log('data: ', data);
}

It looks like you need to send grant_url in the request body (that implies the HTTP request is probably a POST), not as a query parameter, which is what you are doing.

Related

Avoiding http error 405 while executing an put command with angularjs

First to say, when I enter the put command in POSTMAN (its then a POST there) I have no problems. Trying to execute the PUT command in code I receive a http 405 error.
The exact error is:
<p>Problem accessing /api/portfolio/createTransaction. Reason:
<pre> Method Not Allowed</pre></p><hr>
This is my code:
const app = angular.module('demoAppModule', ['ui.bootstrap']);
const apiBaseURL = "/api/portfolio/";
console.log(apiBaseURL);
app.controller('DemoAppController', function($scope, $http) {
const demoApp = this;
demoApp.createTransaction = function () {
console.log("Initiating createTransaction...")
var transactionDetails = $.param({
Reference: $scope.reference,
Quantity: $scope.quantity,
TradeDate: $scope.tradeDate,
});
const createTransactionURL =
apiBaseURL
+ "createTransaction";
console.log("Executing flow");
console.log("Transaction URL = " + createTransactionURL);
console.log("Transaction Details = " + transactionDetails);
$http.put(createTransactionURL, angular.toJson(transactionDetails))
.then(function (transactionDetails, status, headers){
$scope.ServerResponse = transactionDetails;
})
.catch(function (transactionDetails, status, header, config) {
$scope.ServerResponse = htmlDecode("transactionDetails: " + transactionDetails +
"\n\n\n\nstatus: " + status +
"\n\n\n\nheaders: " + header +
"\n\n\n\nconfig: " + config);
});
};
});
Appreciate any help!
The server is rejecting your request, likely because it doesn't allow PUT requests.
It's probably expecting a HTTP POST instead of a PUT.
If so, change $http.put to $http.post - the method signatures are identical.
If you think the server should be accepting a PUT, you'll need to check why the server side code is rejecting it, which won't be apparent in the client code

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'
}
}

Angular HTTP Basic Auth logout header change ignored

I'm using basic HTTP auth (without SSL for testing).
The login works fine, we send an $http request with the authorization header and if the login is correct, it works.
For logout, I'm setting the Authorization header to a bad value and sending an $http request to "trick" the server. The server seems to ignore the new changed auth header. I verified with developer tools in FF that the header value is all ones, but the request is still successful.
How do I "logout"? The logout function sends a bad Authorization header, and the browser sends it according to firebug. What's going on? This is a Java EE 7 app with Wildfly 9 and Shiro, if that makes a difference.
Here is the code:
var DataFactory = function($http, $rootScope, $base64, $cookieStore) {
var _debug = false;
function _d(message) {
if (!_debug) {
return;
}
console.log(message);
}
function setDebug(flag) {
_debug = flag;
}
function doLogout() {
_d("Logging out");
$rootScope.globals = {};
$cookieStore.remove('globals');
$http.defaults.headers.common['Authorization'] = 'Basic 111111111111111111';
$http.get(
'http://localhost:8080/myapp/rest/v1/svc')
.then(function(data) {
alert("Logout: " + JSON.stringify(data.data));
}, function(data) {
alert("Logout Error: " + JSON.stringify(data))
});
}
function doLogin(username, password) {
var token = $base64.encode(username + ":" + password);
_d("Logging " + username + " in with token " + token);
$http.defaults.headers.common['Authorization'] = 'Basic ' + token; // jshint
// ignore:line
$rootScope.globals = {
token : token,
username : username
};
$cookieStore.put("globals", $rootScope.globals);
_d("Login finished, globals are: " + JSON.stringify($rootScope.globals));
$http.get(
'http://localhost:8080/myapp/rest/v1/svc')
.then(function(data) {
alert(JSON.stringify(data.data));
}, function(data) {
alert("Error: " + JSON.stringify(data))
});
}
;
return {
setDebug : setDebug,
doLogin : doLogin,
doLogout : doLogout
};
}
Sending your own authorization string within a XHR request will not magically delete the information cached in the browser. Basic authentication has no concept of logging out. The only way to "logout" with basic authentication is to make the credentials invalid at the server, i.e. change username and/or password so that the stored credentials do not work any longer.

Token base authentication url is not returning response

I am new to AngularJS and Single Page Application in ASP.NET MVC. I am using Web API as service and token based authentication for login. When I am calling authentication URL as below, it is not returning response and then appears to b null.
var data = {
grant_type: "password",
username: userName,
password: loginPassword
};
$http.post("/Token", data)
.then(function (response) {
alert(JSON.stringify( response.data));
return response.data;
});
However when I am passing data as below, it return the response.
var data = "grant_type=password&username=" + userName + "&password=" + loginPassword;
$http.post("/Token", data)
.then(function (response) {
alert(JSON.stringify( response.data));
return response.data;
});
Question: What is actually happening both cases that first is not responding at all, while other is responding?

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