Can Spring-Security control Html+JQuery+Json+SpringRoo project? - spring-mvc

I'm using HTML+JQuery as UI, Spring-Roo to generate service layer which contains Json object string conversion. It works well for us like the following sample code:
#RequestMapping(headers = "Accept=application/json")
#ResponseBody
public ResponseEntity<String> ArticleController.listJson() {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
List<Article> result = Article.findAllArticles();
return new ResponseEntity<String>(Article.toJsonArray(result), headers, HttpStatus.OK);
}
but after several sample pages developed, I have some questions:
1) We want to use Spring-Security as Access Control module, is that OK for this framework? How can server knows it is the same session request from the browser?
2) Instead of jsp server technology, pure HTML + JQuery is really OK? Because I see many Ajax code injected in the html, and many of them cannot be reused. As we know server technologies have the template that can maximizing the reusage of code. I'm worrying about the develop difficulty and maintenance efforts.
PS: Why we decided using HTML+JQuery+Json is because we directly get HTML+CSS from Art designer,
and we have plan to support different client besides browser, so Json might be a good choice.
Thanks.

1) We want to use Spring-Security as Access Control module, [...] How can server knows it is the same session request from the browser?
First the session must be somehow established on the server side. Use standard Spring Security login screen or call spring_security_login using ajax. In return the server will send a cookie with JSESSIONID. This cookie sent with every subsequent request (including AJAX requests) so the server knows which user calls REST methods. This is completely transparent.
Also when you logout (by calling j_spring_security_logout) the session as well as cookies are destroyed.
We are using this approach successfully (more over, due to historical reasons we are calling soap services from JavaScript!) and it works really well.
2) [...]pure HTML + JQuery is really OK? Because I see many Ajax code injected in the html, and many of them cannot be reused. [...]
True separation of concerns is the king. Keep JavaScript in one place (.js) file and HTML in other place (.html). They should never be mixed. Also keep your JavaScript code layered and stay away from DOM manipulations as much as possible (e.g. use client-side templating engines).
Moreover there is nothing preventing you from generating HTML during build so that common HTML snippets like headers and footers are included in every page.

Related

How does Backbone send a PUT and PATH request to server

Regarding this question and also many documents have stated that sending a PUT request directly via form in browser is impossible due to security reason.
However, What I am seeing in Backbone is that it could still send a direct PUT request via browser without a workaround like adding a hidden form field.
And they're confusing to me. Is there anything that I'm missing here?
A form can only send a GET or a POST request, as set in the method attribute.
However, Backbone delegates its requests to jQuery.ajax by default (or whatever you want via Backbone.ajax) which itself wraps XMLHttpRequest, an object that can send PUT/DELETE/PATCH requests.
From https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
XMLHttpRequest is a JavaScript object that was designed by Microsoft
and adopted by Mozilla, Apple, and Google. It's now being standardized
in the W3C. It provides an easy way to retrieve data from a URL
without having to do a full page refresh. A Web page can update just a
part of the page without disrupting what the user is doing.
XMLHttpRequest is used heavily in AJAX programming.
many documents have stated that sending a PUT request directly via browser is impossible due to security reason
Citation please.
Backbone sends a PUT just like it sends any other request, with jQuery,
Backbone.ajax({
type: 'PUT'
...
});
It is just some server side langauges,like PHP, that have problems with receiving a PUT request.
The hidden form field is used when posting from a <form>. Backbone uses javascript.

jQuery Mobile App + remote REST Webservice: Alternatives to JSONP?

Currently I'm working on a jQuery Mobile website which will later be transformed into an app via Titanium. I have created a RESTful JSON web service, which is running on a different server than the jQuery Mobile application. The web service is consumed via AJAX using JSONP.
One thing I find annoying is that I can't make use of HTTP error codes, because jQuery automatically aborts a JSONP call whenever the server issues an error. I can never get hold of the error code on the client side.
Another thing is that JSONP only works with the HTTP verb GET, you cannot issue a JSONP POST for example (Currently, the web service is GET only, but that could change).
Are there any alternatives to JSONP? Or is JSONP the only choice I have when using remote JSON web services with AJAX? For example, how do Twitter apps interact with the Twitter API (they have a REST API)?
Your question is a nice illustration why people complain that jquery is too easy to adopt ;)
JSONP is not ajax. There are no success and failure callbacks. JSONP is this:
put the parameters in the url
add &jsoncallback=random2745273
create a global variable random2745273 and put the callback reference in it
add <script src="theurlhere"></script> to the head
that's all you can do.
The server returns
random2745273({somedata});
and that's how your callback is called.
If you want to report errors, then your server has to generate a correct code. You will not know what HTTP headers were sent.
And this is the only way you can communicate cross-domain with an api.
Sending cross-domain communicates is also possible with generating iframes, but it's hacky and rarely used.
[edit]
Ok, that got me thinking... I could use the iframe hack to wrap over the JSONP!
And as usual - I wasn't the first to have the idea (and I'm finally humble enough to google my ideas expecting it ;) )
Here it is: http://beebole.com/en/blog/general/sandbox-your-cross-domain-jsonp-to-improve-mashup-security/
awesome
[edit2]
awww, I forgot... There's another one.
window.postMessage
It already got implemented in some browsers. If you don't have to be compatible with most of the browsers, you can start using it now! :)
After some more research on postMessage I found an alternative to JSONP: AJAX via Cross-domain messaging with EasyXDM.
See http://easyxdm.net/wp/2010/03/17/cross-domain-ajax/

http post from firefox extension to ASP.NET

I want to be able to send a simple http post from my firefox extension to my ASP.NET application. From the client side, I have used XMLHTTPRequest by sending the post with the url: http://localhost:15227 which is the url on my ASP.NET app.
What do I need to do to receive a remote request from ASP.NET please?
thanks
This page from Apple has a pretty good example of how to send/receive data using a raw XmlHttpReqeust object (as opposed to a JavaScript library).
You can get the value of the response from the responseText property once you know the response came back successfully. Specifically take a look at where the processReqChange function is defined, your code will go in there (or your equivalent of that function).
If you want to explore JavaScript frameworks, take a look at how much less code you need if you use jQuery get (for example).

PageMethods security

I'm trying to 'AJAX-ify' my site in order to improve the UI experience. In terms of performance, I'm also trying to get rid of the UpdatePanel. I've come across a great article over at Encosia showing a way of posting using PageMethods. My question is, how secure are page methods in a production environment? Being public, can anyone create a JSON script to POST directly to the server, or are there cross-domain checks taking place? My PageMethods would also write the data into the database (after filtering).
I'm using Forms Authentication in my pages and, on page load, it redirects unauthenticated users to the login page. Would the Page Methods on this page also need to check authentication if the user POSTs directly to the method, or is that authentication inherited for the entire page? (Essentially, does the entire page cycle occur even if a user has managed to post only to the PageMethod)?
Thanks
PageMethods are as secure as the handler in which they reside.
FormsAuthentication will protect everything except the Login page.
On an unprotected handler, like login, you should expose only methods that 1) are not sensitive or 2) validate the user.
EDIT: in response to comments and other answers regarding CSRF and XSS please see http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx
You're trying to protect against CSRF attacks.
These attacks can be prevented by requiring an authorization code in the POST parameters, and supplying the auth code in the initial page load. (The auth code should be per-IP address and per-user, and should expire quickly)
For added security, you can make each auth-code only usable once, and have each request return a new auth-code. (However, if any request fails, you'll need to reload the page)
I am working on a project that heavily utilizes ASP.Net WebForms Page Methods which I talk to using Ajax. This is rather very convenient for me than writing all my codes in JavaScript.
However, Securing the page methods became an issue which troubled me. I see that I can access the page methods via Postman and Fiddler hence, enabling hackers to play with your APIs.
My solution was quite simple which I discovered accidentally. Adding a static Cookie request to the page method would return error for any app that is NOT the website.
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static string GetAnything(object dat)
{
HttpCookie myguid = HttpContext.Current.Request.Cookies.Get(Constants.Session.PreventHacking);
var hackguid = myguid.Value ?? ""; //other page method contents
return "anything";
}
A postman request to this method would return :
{
"Message": "There was an error processing the request.",
"StackTrace": "",
"ExceptionType": ""}
While a more detailed error would show if on LocalHost.
I understand there are browser ad-ons that can intercept API calls by sitting just beside the website. I have not tested this. A separate security fix has to be built for this however.
I'll update here once I perform some tests.
Think of Pagemethods like a mini webservie local to the page. The fact is they will have no extra checks and verifications in place except those that are placed on the entire website, and those that you choose to put in.
Using Pagemethods is a smart idea from the point of view of 'Encapsulation', and if you're going to use them it doesn't hurt trying to put in some extra security measures in place.

What is the difference between HttpHandler and a Web User Control and when to use each one?

I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong
Unfortunately your question is a little like "Should I use a sandwich or a cement mixer". HttpHandlers and User controls are completely different things.
HttpHandlers are used to process HTTP requests. For example, if you wanted to dynamically create an RSS feed, you could write an HTTP handler that handles all requests for ".rss" files, creates the output and sends it back to the user.
User controls are used within ASPX pages to encapsulate units of functionality that you want to re-use accross many pages.
Chances are, if you're using user controls successfully, you don't want to use HttpHandlers!
Basically a user control is a piece of server logic and UI. An HTTP Handler is only a piece of logic that is executed when a resource on your server is requested. For example you may decide to handle requests for images sent to your server through your own handler and serve images from a database instead of the file system. However, in this case there's no interface that the user sees and when he visits a URL on your server he would get the response you constructed in your own handler. Handlers are usually done for specific extensions and HTTP request types (POST, GET). Here's some more info on MSDN: http://msdn.microsoft.com/en-us/library/ms227675(VS.80).aspx
Expect a better answer (probably before I finish typing this) but as a quick summary.
A user control is something that can be added to a page.
A HttpHandler can be used instead of a page.
Just to clarify the question. I was reading the Hanselman post
http://www.hanselman.com/blog/CompositingTwoImagesIntoOneFromTheASPNETServerSide.aspx
and thinking that I would never solved the problem with a HttpHandler, maybe with a simple page returning a binary content.
This led me to think that I should add HttpHandler to my developer tool belt.
Even an Asp.Net page is an HttpHandler.
public class Page : TemplateControl, IHttpHandler
A user control actually resides within the asp.net aspx page.

Resources