Token authorization - Browser throws Login form - angularjs

I am working on a token implementation into Angular/.Net application. My part is the front-end. What's happening is that when UI sends a request with the expired token and the server replies with 401 I cannot intercept that before the Browser raises the Login form. As the result I cannot send a request to refresh the token. Can someone please give me an idea how that is supposed be managed? I will provide code just don't know what's to show.
Thanks
Adding code:
var response = $http({
method: "GET",
dataType: "json",
params: params,
headers: {
'Content-Type': "application/xml; charset=utf-8",
},
url: someurl
});
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
The problem is that I cannot redirect on UI because Browser throws Login form before my code is hit when the server returns 401.

Make ajax request, and if you get 401 then redirect to login page.
P.s. for better understanding provide your code how you implement ajax request. Which module do you use for front-end auth? I recommend satellizer
Added:
I guess you need the following configuration on angular
var app = angular.module('App', ['satellizer'])
.config(function() {
/* your config */
}
.run(function($rootScope, $location, $auth) {
// Check auth status on each routing,
// Redirect to login page, if user is not authenticated or if token expired
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$auth.isAuthenticated()) {
$location.path('/auth/login');
}
});
});

Related

Angularjs $http service passing facebook access token

I'm implementing fb authentication in my SPA built using MEAN stack. While I've successfully implemented the fb authentication using facebook token passport strategy, I'm facing issues in securing API endpoints. Because for that I need to pass both the authenticated user object and access token in the $http service and I've tried passing access_token as a property of the user object and also as a header property, but I still 401 (Unauthorized error). Below is my code snippet.
Passport documentation says "Authorization: Bearer base64_access_token_string". Should the token be encoded in a base64 format? Pls help.
server code
app.get('/api/getbikes*',
passport.authenticate('facebook-token',{session: false}),
function(req,res){
if(req.user){
console.log('In getbikes api');
// console.log('req.query :',req.query);
var msg="";
ubBike
.find({cust:req.query._id})
.populate('cust','email')
.exec(function(err,bikes){
res.send(bikes);
if(err) throw err;
});
}
else
{
res.send(401);
}
});
angular code
service
this.getbikes = function(user){
var deferred = $q.defer();
$http({
method:"GET",
url:"http://localhost:3000/api/getbikes",
params: user,
headers:{
Authorization:auth.getAccesstoken()
}
}).then(function successCallback(srresponse){
deferred.resolve(srresponse.data);
},
function failureCallback(srresponse){
$log.error("get bikes http call failed ",srresponse.data);
deferred.reject(srresponse.data);
});//$http
return deferred.promise;
};//getbikes
controller
$scope.fblogin= function(){
auth.fblogin().then(
function(response){
$scope.isAuth = auth.isAuth;
$scope.usr =auth.getResponseobj();
$scope.usr.access_token=auth.getAccesstoken();
$scope.profpic=auth.profpic;
bike.getbikes($scope.usr).then(function(response){
if (response.length ==0)
{
$location.path('/addbike');//redirect to addbike screen
}
else{
$location.path('/appoint');//else redirect to view appointment screen
}
},function(reason){
$scope.msg1 = reason;
});//getbikes
},function(reason){
$log.log("fblogin() - failure :Need to login to the application :"+reason);
})
};//fblogin
Surprisingly, when I send the header as "Authorization: Bearer access_token_string" ie the fb token as is without base64 encoding the API authentication works perfectly fine. This is contrary to the passport facebook token documentation https://github.com/drudge/passport-facebook-token

cant update another user details while logged in

I'm working on nodejs loopback application. I've a user logged in already and and an operation requires this user to find a userById and update a field.
$scope.user = User.findById({
id: sender.id
});
$scope.user.supplierId = currUserId;
$scope.user.$save();
But its not working as required.
and I get following error:
PUT http://localhost:5000/api/users 401 (Unauthorized)
GET http://localhost:5000/api/AuthProviders/count 401 (Unauthorized)
401 while on router on login path
POST http://localhost:5000/api/users/login?include=user 400 (Bad Request)
Any help will be appreciated.
Thanks
For findById operation:
var url = 'http://localhost:3000/api/User/' + sender.id + '?access_token=h9vpJ94zqN199ENWx'
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(error) {
throw error;
});
Otherwise you can use Angular SDK which makes it much cleaner.

Angular $http post with custom headers

I am new to angular and am from .net framework. I need to post a angular request to .net service, where it expects two custom headers from the client.
angular post command:
var request = $http(
{
url: "http://localhost:53585/api/myService/Validate",
method: "POST",
data: JSON.stringify(payload),
headers: { 'first_token': sessionService.first_token, 'second_token': sessionService.second_token }
});
But in the service side, I can see only first_token in the request header and not the second token. What I am missing here?
Issue is with my service. I figured out and restarted the IIS and then service was able to read both the headers token
I found this method in a forum, it works.
return this.http.post<any>('https://yourendpoint', { username, password }, { headers: new HttpHeaders().set('Authorizaion', 'your token')})
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// sto`enter code here`re user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
console.log(user);
return user;

AngularJs optional header param (token)

My app is using token based auth, but a guest can get data too. So for requesting data, I decided to use ngResource lib and write a factory for it.
First, the auth controller gets a token from the server and places it to localstorage. After that $place proceeds to the home page where the home controller requests data through Home factory.
My problem is that if I use guest mode and then authorize with user data, my app can't add the token header to $resource object.
After reload page everything is working properly, but I need do it without reloading. Here is my factory code
.factory('placeResource', ['$resource','$window', function($resource,$window) {
var get_token = function(){
if ($window.localStorage.token){
return 'token '+$window.localStorage.token
}
};
return $resource("/api/:resourceName/place/:placeId",
{ resourceName: '#_resourceName', placeId: '#placeId'},
{
query: {
method: 'GET',
isArray: true,
headers: { 'Authorization': get_token() }}
}
);
}]);

Status Code 302 found on POST request using Angular, Revel and Go

I am using Revel + angular for my application. The index page is the login interface, and once you are successful, you should be directed to the dashboard.html page. The problem is once I have made a POST request, I get a GET request with my 'response body', however, I am still in the login page. I am using angular to make a post request to my restful server. However, whenever I make a POST request I get status 302 on my POST request but my GET request fetches the response for the page.
My Angular Controller
appMainLogin.controller('MainLoginForm',function($scope, $http){
$scope.user_email = null;
$scope.user_pass = null;
$scope.user_remember = true;
$scope.userLogin = function () {
var val = {
"user_email": $scope.user_email,
"user_pass": $scope.user_pass,
"user_remember": $scope.user_remember,
};
var stringify = JSON.stringify(val);
$http({
url: '/login',
method: 'POST',
data: stringify || '',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}
}).success($scope.getEmailData).error($scope.httpError);
alert("error");
};
});
My routes
POST /login App.Login
GET /dash Dash.Index
I get this: 302 on the POST request
I get this: 200 OK on the GET request
On the 'response body' of the GET request (firefox debugger) I see my I intended html page but I still remain in the index page.
Why is my app not redirecting to the dashboard.html(index.html->dashboard.html) after the user enters their login credential (based on my code above)?

Resources