Authendicated video playback using angularjs - angularjs

I'm working on an angularjs SPA type project and there I came across a situation where i need to play an ordinary mp4 file, but the issue is that video is not public so in order to access it i need to send an access token in header.
so my question is
If this is possible how do i do the playback
is token based authentication is a right approach to securely access a media

At the end I came up with this code, code you see is a part of a directive
var video = $http({
method : "GET",
url : "http://path/small1.mp4",
responseType : "blob",
headers : { X-Access-Token : "token" }
});
video.success(function(data,status,headers,config){
if((data != undefined)){
var dataURL= window.URL.createObjectURL(data);
$scope.videourl = dataURL;
//window.location =dataURL;
var video = document.getElementById("emptyvideo");
video.src = dataURL;
video.addEventListener('error', function(err){
// Nothing to see here...
console.log(err);
// Will throw a MediaError code 4
console.log(video.error);
});
}else{
alert("error");
}
});
video.error(function(data,status){
alert("error");
});
This is fine for small videos, but if the video got bigger this is not a good apporach. because in this code video need to be fully loaded in order to do a playback, please suggest me if there is a better apporach

In order not to loose streaming ability, the best (if not the only) way is to secure static videos with an access token passed as an url parameter. I mean you need to give up authentication via token in header.
So you need to make changes to your service on your server to authenticate request by query parameter.
For example your url will look like: www.yourawesomeserver/your_video?access_token=ue873wijweu383j3
Your server should serve the static file if the token is OK.

Related

Error 400 when POST'ing JSON in angularjs + Spark Single Page Application

I'm new to Single Page Application area and I try to develop app using angularjs and Spark framework. I get error 400 bad request when I want to post JSON from my website. Here is code fragment from client side:
app.controller('PostTripCtrl', function($scope, $http) {
$scope.newTrip = {};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:4567/trips/add',
data : $scope.newTrip,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
}).success(function(data) {
console.log("ok");
}).error(function(data) {
console.log("error");
console.log($scope.newTrip);
});
};
});
Values that are to be assigned to newTrip are read from appropriate inputs in html file. Here is server-side fragment:
post("/trips/add", (req, res) -> {
String tripOwner = req.queryParams("tripOwner");
String startDate = req.queryParams("startDate");
String startingPlace = req.queryParams("startingPlace");
String tripDestination = req.queryParams("tripDestination");
int tripPrice = Integer.parseInt(req.queryParams("tripPrice"));
int maxNumberOfSeats = Integer.parseInt(req.queryParams("maxNumberOfSeats"));
int seatsAlreadyOccupied = Integer.parseInt(req.queryParams("seatsAlreadyOccupied"));
tripService.createTrip(tripOwner, startDate, startingPlace, tripDestination, tripPrice, maxNumberOfSeats,
seatsAlreadyOccupied);
res.status(201);
return null;
} , json());
At the end I obtain error 400 bad request. It is strange for me that when I want to see output on the console
System.out.println(req.queryParams());
I get json array of objects with values written by me on the website. However, when I want to see such output
System.out.println(req.queryParams("tripOwner"));
I get null. Does anyone have idea what is wrong here?
I think the main problem is that you are sending data to your Spark webservice with the 'Content-Type' : 'application/x-www-form-urlencoded' header. Try sending it as 'Content-Type' : 'application/json' instead, then in your Java code declare a String to receive req.body(), you'll see all your data in there.
Note: When you try to acces your data like this req.queryParams("tripOwner"); you're not accessing post data, but you're seeking for a get parameter called tripOwner, one that could be sent like this http://localhost:8080/trips/add?tripOwner=MyValue.
I would advise using postman to post a request to your server and see if it works. Try a different content type too. Try using curl and play with the various headers you are sending. 400 suggests the wrong data is being sent or expected data is missing or the data is the wrong type but based on your code you've provided I can see nothing wrong (but see below).
When your server receives a request log all request headers being received and see what changing them does. If it works in postman then you can change your client code to mirror the headers postman is using.
Does your spark server validate the data being sent before your controller code is hit? If so ensure you are adhering to all validation rules
Also on looking at your code again your client is sending the data in the post data but your server is expecting the data in the query string and not in the post data?
What happens if your server just sends a 201 response and does nothing else? Does your client get a 201 back? If so it suggests the hook up is working but there is something wrong with the code before you return a 201, build it up slowly to fix this.
Ok, I managed to cope with that using another approach. I used Jackson and ObjectMapper according to Spark documentantion. Thanks for your answers.
You can see more about that here: https://sparktutorials.github.io/2015/04/03/spark-lombok-jackson-reduce-boilerplate.html
You're probably just needed to enable CORS(Cross-origin resource sharing) in your Spark Server, which would have allowed you to access the REST resources outside the original domain of the request.
Spark.options("/*", (request,response)->{
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if(accessControlRequestMethod != null){
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
Spark.before((request,response)->{
response.header("Access-Control-Allow-Origin", "*");
});
Read more about pre-flighted requests here.

I am uploading the image file in Angular Js to call the java api but my form data is not hitting the api

controller:
$scope.fileToUpload = function(input) {
if (input.files && input.files[0]) {
CommonService.uploadContactImage.upload({
fileName : input.files[0].name
}, input.files[0], function(data) {
});
}
}
Service:
uploadContactImage:function(input){
console.log("game image");
var req = $http({method: 'POST', url: options.api.base_url + '/gameimageupload/',
dataType: 'json', headers: {'Content-Type': undefined}})
.success(function (data)
{
console.log("data" + data);
return data;
});
If you take a good look at your code you will see that there are quite a few things wrong with it. For example, you have defined in your service an uploadContactImage function which takes a single Javascript object as argument (input), while in your controller you attempt to call CommonService.uploadContactImage.upload(...) instead of CommonService.uploadContactImage(...). Additionally, even if the uploadContactImage function was called correctly it doesn't actually do anything with its argument, ie. the input object is never used in the function body.
These issues aside you cannot submit a file to the server just by adding it to the body of a POST request the way you (seem to be) trying to do. Without going into too much detail here, in order to upload a file from the browser a request with content type multipart/form-data needs to be submitted, which will contain your file as well as the necessary HTTP headers for the server to identify it and parse it correctly. I suppose you could try and construct this request yourself, however it's not a task for the faint-hearted. What I would suggest instead is to use one of the many file upload modules available for Angular.js. A Google search will give you quite a few modules that you can check out to see which better fits your needs.

upload file to RESTful service in angularjs

i try to make angular CRUD app that is a bit like "dropbox". So, it must have file and folder hosting with sharing and access functionality. I'm stuck on a question how to upload image and video files? I used File API (FileReader, Blob) to make preview of files on the client side but i dont have idea how to POST this type of data to server.
Something like this should work well to send as multipart/form-data request to backend API:
var file = ... // get from file input;
var backendUrl = ...
var fd = new FormData();
fd.append('myFile', file, 'filename.ext');
$http.post(backendUrl, fd, {
// this cancels AngularJS normal serialization of request
transformRequest: angular.identity,
// this lets browser set `Content-Type: multipart/form-data`
// header and proper data boundary
headers: {'Content-Type': undefined}
})
.success(function(){
//file was uploaded
})
.error(function(){
//something went wrong
});
See here for reference:
FormData API Doc
Using FormData Objects (MDN)
multipart-formdata file upload with AngularJS
You can upload file using ngFileUpload or angularFileUpload directives.
In case of angularFileUpload, you use .upload in controller and in case of ngFileUpload, you use .http
Also, you can also use application/x-www-form-urlencoded content type instead of multipart provided your file is not huge. In case of application/x-www-form-urlencoded, you can just receive the value in rest webservice as normal InputStream thereby requiring no need of marshalling of multipart data.
You may refer the below for the possible ways to upload file using angular js and rest web service:
http://technoguider.com/2015/08/file-upload-using-angular-js-and-rest-web-service/

How works simple table load with AngularJS?

I'm trying to learn AngularJS starting with that example: http://jsfiddle.net/mjaric/pJ5BR/
but when I tried to download in localhost, not works. I think that is a URL problem in /echo/json':
$scope.loadPeople = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
$scope.people = data;
});
};
But I don't know how to solve it. Any idea or hint?
My finally idea is load json from a search petition. It's possible that 'data' will be charged from web or online.
The url: '/echo/json/' is a feature of JsFiddle. If you look at the tabs to the left, in Ajax Requests you can see the usage. It probably won't work with this url in localhost.
You need to create a web project, where you can send your request. You could send some search parameters from client side, then filter the data with those parameters in the server and then return the filtered data to show.
The following article will give you some good ideas
http://tutorials.jenkov.com/angularjs/ajax.html
This link provides a hands on example by a really good tutor.
http://weblogs.asp.net/dwahlin/learning-angularjs-by-example-the-customer-manager-application

Recaptcha angularjs verify user's answer

I am using the following plugin https://github.com/VividCortex/angular-recaptcha in order to use recaptcha at a login form.
I am using the following code for verification
$http({
url: 'https://www.google.com/recaptcha/api/verify',
method: 'POST',
params: {privatekey: "key", remoteip: "userip", challenge: "challenge", response: "user_answer" },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {
console.log(data);
if (valid) {
console.log('Success');
alert('Success');
} else {
console.log('Failed validation');
alert('Fail');
// In case of a failed validation you need to reload the captcha because each challenge can be checked just once
//vcRecaptchaService.reload();
}
});
But google server is not returning anything.
I updated the code but no luck.
I think you have a typo in your code:
post: 'GET'
Change that to method: 'GET' or method: 'POST'.
You can check out angular documentation on http to make sure you've written all the params right.
If this wasn't the source of your problems, you should post more details about your issue (what do you see in your networkl console for example).
Keep in mind that recaptcha validation must be done at server-side. I'm not 100% sure that you are doing that in the browser, but your code looks like it.
As Miguel Trias stated, you shall not validate directly from angularjs/javascript client, instead you should send the challenge and response field to your server and validate then.
Therefore you can use the uri you used (https://www.google.com/recaptcha/api/verify) or a plugin, e.g. if you use php see https://developers.google.com/recaptcha/docs/php. I'd prefer a plugin because it will save work.
Furthermore keep in mind that your private key should not be used in the client, this is why it is called private. It is only used to communicate between your server and the reCaptcha servers. The public key is used to communicate between your client and the reCaptcha servers.
For more info read the Overview

Resources