CSRF in grails, withForm{}.invalidToken{} not working fine - security

As I've to use csrf in my grails application, I'm doing it by encapsulating my action logic under withForm{...}.invalidToken{....}, also I'm adding an attribute as: g:formRemote useToken="true" under g:formRemote tag in gsp.
The problem is, I'm always getting inside the invalidToken{...} block on submit and hence my form is not getting saved.
How should I make it working properly?
Example:
def action = {
withForm{
......
}.invalidToken{
println "Invalid Token code"
}
}
gsp ex:
<g:formRemote useToken="true" ...>
...
...
</g:formRemote>

useToken is not supported with formRemote. Please take a look on https://github.com/grails/grails-core/blob/2.5.x/grails-plugin-gsp/src/main/groovy/org/codehaus/groovy/grails/plugins/web/taglib/JavascriptTagLib.groovy#L349
The supported attributes for formRemote are:
* #attr name REQUIRED The form name
* #attr url REQUIRED The url to submit to as either a map (containing values for the controller, action, id, and params) or a URL string
* #attr action The action to execute as a fallback, defaults to the url if non specified
* #attr update Either a map containing the elements to update for 'success' or 'failure' states, or a string with the element to update in which cause failure events would be ignored
* #attr before The javascript function to call before the remote function call
* #attr after The javascript function to call after the remote function call
* #attr asynchronous Whether to do the call asynchronously or not (defaults to true)
* #attr method The method to use the execute the call (defaults to "post")
With that said. You can keep using the withForm in your controller and implement the form submission using jQuery or other JS library and send the token. Please take a look at this question: Grails - Is there a recommended way of dealing with CSRF attacks in AJAX forms?
Also I would recommend you to move on from tags like formRemote. I'm assuming you're using at least Grails 2.x. In case you want to migrate to Grails 3.x in the future, the Ajax-related tags are deprecated.
Hope this helps.

Related

Get real requestURI without appended index.xhtml when welcome file is used

So here are 2 requests:
http://example.com/someUrl/
http://example.com/someUrl/index.xhtml (xhtml extension is not relevant just an example)
When the <welcome-file>index.xhtml</welcome-file> is been set, request 1 is handled by the server as 2.
However, in both cases the request.getRequestURI() returns the complete URI: someUrl/index.xhtml.
According to documentation it shouldn't but in most cases it's what we want so it seems fine it does.
I'm working with JSF under JBoss Wildfly (Undertow webservice) and I don't know which one is responsible.
I don't necessarily want to change how it works but I'm looking for a way of getting the original URI as the enduser sees in browser address bar, thus without the index.xhtml part in case of 1.
To be more precise, I have to get the exact same URL as returned by document.location.href in JavaScript.
The welcome file is been displayed by a forward which is under the server's covers been performed by RequestDispatcher#forward(). In that case, the original request URI is available as a request attribute with a key as identified by RequestDispatcher#FORWARD_REQUEST_URI, which is javax.servlet.forward.request_uri.
So, this should do:
String originalURI = request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
if (originalURI == null) {
originalURI = request.getRequestURI();
}
// ...

pyramid: constructe route_url without request object

I use yapps to generate a parser for a LaTex-ish language (for example to translate stuff like \begin{itemize} to the corresponding <ul>-Tags) within pyramid. One command (i.e. \ref{SOMEID}) should construct a route via a call of route_url (or route_path) and pass the id to it. Since this call happens deep in the code that was generated by yapps and the grammar that I defined, I don't see any possibility to pass a request object to it.
Is there some sort of global request object? Or, since I foresee that I shouldn't use it, is there a possibility to construct a route (that depends on a parameter) without a request object?
route_url requires both a request and a registry (request.registry). It generates urls relative to the request, and it accesses the list of all routes and other settings from the registry. Thus, you must generate a dummy request with parameters you care about. For example:
from pyramid.request import Request
request = Request.blank('/', base_url='https://example.com/prefix')
request.registry = config.registry
Now you can store this request anywhere, it's good to go representing everything about your site: the hostname/port (example.com:443), the prefix your app is mounted at (/prefix), the uri scheme (https).
If you need to get this deep down into your code you may have to make it a global or attach it to some context/registry that you have available, but what I've shown is how to make the request that you require.

Notification in ajax response orchard

I'm using ajax requests to get one of PartialViews in my project. I want to pass a message by INotifier.
Cuttently i'm using HttpStatusCodeResult return new HttpStatusCodeResult(204, "Message");to pass informations about the errors but is not satisfying solution.
$(this).load($(this).attr("href"), function (response, status, xhr) {
if (xhr.status == 204) {
// show message
}
});
I'm wondering that is possible by using standard INotifier.Error() in ActionResult.
Nope. The default notifier is not suitable for AJAX requests. What it does, it queues notifications inside a temporary collection. Queued notifications are then written to the client when request ends - pushed into Layout.Messages zone.
In your case it would be best to implement your own INotifier that would follow the required logic. It's a very simple interface to implement so it's not actually that much work.
I needn't to implement INotifier, i only placed in my PartialView this:
#Display(WorkContext.Layout.Zones["Messages"])
Now the message isn't rendered in main zone (in Layout.cshtml of used theme), but could be placed anywhere in your PartialView, for example under the affected table.

Monotouch/iPhone - Call to HttpWebRequest.GetRequestStream() connects to server when HTTP Method is DELETE

My Scenario:
I am using Monotouch for iOS to create an iPhone app. I am calling ASP.NEt MVC 4 Web API based http services to login/log off. For Login, i use the POST webmethod and all's well. For Logoff, i am calling the Delete web method. I want to pass JSON data (serialized complex data) to the Delete call. If i pass simple data like a single string parameter as part of the URL itself, then all's well i.e. Delete does work! In order to pass the complex Json Data, here's my call (i have adjusted code to make it simple by showing just one parameter - UserName being sent via JSON):
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost/module/api/session/");
req.ContentType = "application/json";
req.CookieContainer = jar;
req.Method = "Delete";
using (var streamWrite = new StreamWriter(req.GetRequestStream()))
{
string jSON = "{\"UserName\":\"" + "someone" + "\"}";
streamWrite.Write(jSON);
streamWrite.Close();
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
on the server, the Delete method looks has this definition:
public void Delete(Credentials user)
where Credentials is a complex type.
Now, here's the issue!
The above code, gets into the Delete method on the server as soon as it hits:
req.GetRequestStream()
And hence the parameter sent to the Delete method ends up being null
And here's the weird part:
If i use the exact same code using a test VS 2010 windows application, even the above code works...i.e it does not call Delete until req.GetResponse() is called! And in this scenario, the parameter to the Delete method is a valid object!
QUESTION
Any ideas or Is this a bug with Monotouch, if so, any workaround?
NOTE:
if i change the Delete definition to public void Delete(string userName)
and instead of json, if i pass the parameter as part of the url itself, all's well. But like i said this is just a simplified example to illustrate my issue. Any help is appreciated!!!
This seems to be ill-defined. See this question for more details: Is an entity body allowed for an HTTP DELETE request?
In general MonoTouch (based on Mono) will try to be feature/bug compatible with the Microsoft .NET framework to ease code portability between platforms.
IOW if MS.NET ignores the body of a DELETE method then so will MonoTouch. If the behaviour differs then a bug report should be filled at http://bugzilla.xamarin.com

Persist url parameter throughout grails app

Essentially I am looking to have a url query parameter persist throughout the life of the grails application (POST or GET). ex.
http://localhost:8080/demo/controller/action/?myParam=foobar
I have tried a couple routes. Dynamic method overriding redirect and customizing application tags for createLink. However, since I also use grails webflows it doesn't quite get every single URL. I also tried using a groovy servlet (groovlet) to capture every URL and append the query parameter. The last attempt hasn't been very successful. Am I missing an obvious component to grails? Am I on the right track? Is there another avenue I haven't explored yet?
Thanks in advance
Have you tried using a filter? The following filter will add the param to every request
class MyFilters {
def filters = {
addParam(controller:'*', action:'*') {
before = {
params.myParam = 'foobar'
}
} } }

Resources