rest,grails,spring-security , Intercepting login calls with Spring-Security-Rest plugin in Grails

Intercepting login calls with Spring-Security-Rest plugin in Grails


Tag: rest,grails,spring-security

I am using the spring security rest plugin for Grails to provide a login mechanism for an AngularJS app. Login works fine, but I can't figure out how to intercept login calls, in order to store additional statistics on (invalid/valid) login attempts.

As I am quite new to Spring Security I am not familiar with it's filter chains. Is it possible to write a custom filter to intercept login calls without interfering with the plugins's mode of action or is there a better way to achieve what I want to do?

I saw that the Spring Security Rest plugin has a class called RestAuthenticationSuccessHandler which implements Spring Security's AuthenticationSuccessHandler interface. Can I provide a custom implementation of the class which is used by the plugin?

My configuration:

grails.plugin.springsecurity.rememberMe.persistent = false = true = 401 = true = 'example.auth.AuthenticationToken' = 'token' = 'username'

grails.plugin.springsecurity.filterChain.chainMap = [
    '/auth/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter, -rememberMeAuthenticationFilter', // Stateless chain
    '/api/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter', // Stateless chain
    '/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'   // Traditional chain


Yes, you can provide a custom bean that implements the RestAuthenticationSuccessHandler. Take a look at the API documentation for the class to see what you need to implement. Then it's as simple as overriding the bean in your application context:

// Resources.groovy
restAuthenticationSuccessHandler(MyCustomRestAuthenticationSuccessHandler) {
  renderer = ref('accessTokenJsonRenderer')

It might also be helpful to look at the default implementation to base yours on.


Do we HAVE to generate and use client libraries to use Google App Engine's Endpoints?

I am currently developing an Swift iOS app with GAE Endpoints for the RESTful API. It seems like all the tutorials and documents make you generate and use client libraries if you need to use the API on the client side. I was wondering if it's possible for me to...

Grails logging auto inject

I use grails 3.0.2 and logback. How can I use this logger in my code, can I somehow autoinject it, like log.debug() in grails 2.x which was using org.apache.commons.logging.Log?

In simple RESTful design, does PATCH imply mapping to CRUD's (ORM's) “update” and PUT to “destroy”+“create” (to replace a resource)?

I'm trying to create a simple REST API and map it to CRUD. I have an ORM (DataMapper) which has methods like create, update and destroy. If I get it right, given a resource {a:'foo',b:'bar',c:'baz'}, performing a PUT {b:'qux'} is supposed to replace the resource and result in the same...

Intercepting login calls with Spring-Security-Rest plugin in Grails

I am using the spring security rest plugin for Grails to provide a login mechanism for an AngularJS app. Login works fine, but I can't figure out how to intercept login calls, in order to store additional statistics on (invalid/valid) login attempts. As I am quite new to Spring Security...

How to avoid abusive use of REST endpoint [closed]

how can I avoid abusive use of my REST API? For example, I have a website where certain actions earn a bunch of points which are stored within a user account. So technically, when ever this action is performed, I call my REST endpoint to add the points to the...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types

While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

How to expose existing REST API through Azure Service Bus (or through something else)

I have an existing on-premise REST API from an external vendor. I'd like to expose this API unmodified to the outside world through an Azure website. So I have customers that run this API on-premise and I'm developing a PaaS/SaaS app that should access these on-premise API's. I also have...

RESTful routing best practice when referencing current_user from route?

I have typical RESTful routes for a user: /user/:id /user/:id/edit /user/:id/newsfeed However the /user/:id/edit route can only be accessed when the id equals the current_user's id. As I only want the current_user to have access to edit its profile. I don't want other users able to edit profiles that don't...

AngularJS $resource Custom Action for Requesting a Password Reset

I'm just starting to use ngResource in a project to consume my RESTful endpoints. Is this how you would implement a user password reset using $resource? Looks weird passing the email address as a URL parameter. .factory('User', ['$resource', function ($resource) { var paramDefaults = {id: '@id'} var actions = {...

Grails: Carry forward params on g:actionSubmit is clicked

How to carry forward the parameters when g:actionSubmit button is clicked? Here is my gsp code: <g:checkBox name="msgCheck" checked="" value="${userInstance.emailId}"></g:checkBox> ... <g:actionSubmit class="update" action="delete" value="Delete" params="${params}"></g:actionSubmit> Here is my controller code: def delete() { try { def user_list = params.msgCheck //deleting the user //successful. redirect(action: "list", params: params) } catch...

remote data fetching inside model object in objective c using AFNetworking

In all of my iOS application I use this approach to respect MCV, I want to be sure that my implementation is correct and respects the best practices and the MVC design pattern : Singleton of AFNetworking acting as API for network calls: MyAPI.h : #import "AFHTTPSessionManager.h" #import "AFNetworking.h" @interface...

Error when using angular with Grails

Here is my index.gsp <!DOCTYPE html> <html ng-app="myApp"> <head> <title>my app</title> </head> <body> <input type="text" data-ng-model="test"/> {{test}} </body> <script src="/js/angular.min.js"></script> </html> When I build an app, There is an error like this, Uncaught Error: [$injector:modulerr]$injector/modulerr?p0=myApp&p1=Error%3A%…20at%20d%20(http%3A%2F%2Flocalhost%3A8000%2Fjs%2Fangular.min.js%3A17%3A381)...

REST API with token based authentication

I want to develop a web site with AngularJS. On the backend side I will use Codeigniter REST framework. I have some security issues and I don't want to start developing without fixing them on my mind. I don't want to use something like api key because it will be...

passing backbone collection to view

I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work. I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will...

Mailchimp Ecommerce360 Javascript Implementation

Wondering if anyone can provide an example of how to pass a request to the /ecomm/order-add function of the Mailchimp API using javascript. This is critical for making use of Mailchimp's Ecommerce360 tracking. Here is documentation from Mailchimps API:

Stuck with nested serializer using Django Rest Framework and default user

The models and serializers are described in the pastebin: In my database I have a user which also has a member profile and a set of credentials attached to it. Now... when I run this as is and try to pull a user using the AuthUserModelSerializer I get the...

Trying to write a unit test for file upload to a django Restless API

I'm writing a fairly small lightweight REST api so I chose restless as the quickest/easiest support for that. I didn't seem to need all the complexity and support of the django-REST module. My service will only received and send json but users need to upload files to one single endpoint....

grails 3.0.1 scaffolded view does not show domain relationship

I am following the example in the book "Grails a Quick-Start Guide" using Grails 3.0.1 with following domains package com.tekdays class TekEvent { static constraints = { name() city() description maxSize:5000 organizer() venue() startDate() endDate() } String city String name TekUser organizer String venue Date startDate Date endDate String description...

How to respond in Middleware Slim PHP Framework

I am creating middleware for auth into REST API. My API is created using Slim PHP Framework ,which in case provide great features to build APIs. One of this feature is Middleware. I need to check credentials in Middleware and respond with an error (HTTP code with JSON descriptions) to...

Laravel: Retrieve polymorphic attributes efficiently

My actual Question is: How to return attributes to the client which I actually need, throw the rest away and be as efficient as possible? So, I have a construction where I basically have media objects, which can be of different types, like video, picture, link and so on. This...

Default/Constant values for POST/PUT arguments with Retrofit

Using the Retrofit REST Client library from Square, is there anyway of providing default/constant values for POST/PUT fields in a call. I know about including constant query parameters by simply including them in the path, but this work for Body parameters. I have an API that looks similar to: POST...

Unable to select values from the select list

my select list is getting populated via a service call but I cannot select any of the values from the select list. AJS.$("#select2-actor").auiSelect2( { placeholderOption: 'first', formatResult: function(actor) { return '<b>' + actor.text ; }, data: function () { var data = []; AJS.$.ajax({ dataType: 'json', type: 'GET', url: AJS.params.baseURL+"/rest/leangearsrestresource/1.0/message/list/{actor}",...

Ruby on Rails - Help Adding Badges to Application

I'm creating a rails application that is a backend for a mobile application. The backend is implemented with a RESTful web API. Currently I am trying to add gamification to the platform through the use of badges that can be earned by the user. Right now the badges are tied...

Log Grails Pre 3.0 startup time

In Grails 2.x.x is it somehow possible to log the startup time? We are currently trying to optimize the application startup and having the startup time logged would help tremendously.

How can I get json objects without the object number?

I have a simple json object that spits out 4 items that have completely different properties inside each one. I have got the json being displayed with the 4 objects that are called meta.work_content like so: [Object, Object, Object, Object] I can open these in console and see the objects...

Grails 3.0 Searchable plugin

I've tried to use the searchable plugin in grails 3.0, but I am not sure wheather it is compatible or not. I've added compile "org.grails.plugins:searchable" to the dependencies. The build completes but yields a NotSearializableException: > Configuring > 1/1 projects > Resolving dependencies ':agent' > Resolving dependencies ': BUILD SUCCESSFUL...

Consuming and exposing webservices in one project (.NET)

What is best practice concerning consuming and exposing webservices in one project? (.net) I need to create a rest webservice to expose data. The rest webservice would need to consume this data from another (SOAP) webservice from a third party. (The data needs to be merged with data present in...

Adding authorization to routes

I cannot seem to find a good example for this. I have for example, a TicketController I define a ticket resource in my routes.rb. You only need to be logged in as a customer to GET a ticket, but you must be logged in as an administrator to PUT a...

grails DataSource.groovy refer bean for decoding password

Referring, we need to specify a class with static methods to decode the encrypted password in DataSource config. For passwordEncryptionCodec property, is it possible to refer to a bean defined in resources.xml or any other grails bean definition files? For ex: having a decrypted Properties bean in resoures.xml or...

Can't save json data to variable (or cache) with angularjs $http.get

I have weird angularjs problem. I'm trying to fetch data from Rest Webservice. It works fine, but I can't save json data to object. My code looks like: services.service('customerService', [ '$http', '$cacheFactory', function($http, $cacheFactory) { var cache = $cacheFactory('dataCache'); var result = cache.get('user'); this.getById = function(id){ $http.get(urlList.getCustomer + id).success(function(data, status,...

How to declare javascript asset in the view to be rendered within the footer using Grails Asset Pipeline

Since there is no deferred option for: <asset:javascript src="custom_view_script.js"/> What else can be used, outside of resource plugin, to place view specific script right before the closing body tag and without declaring it globally in layout? I do know about: <asset:deferredScripts/> but that only handles on page script and not...

How to manipulate local files with webdav

Hi so I just found out that webdav protocol allows for manipulations of local files through a browser. I have it already set up in the back end. What I would like to know is how to make it work on front end. I am using javascript with jQuery. For...

.NET web service gets null object

I'm trying to save an object using ajax call and .NET REST web service but I get null object on .NET side. Please help me to find out what's the issue. C# Object: [DataContract] public class Customer { [DataMember] public int Id { get; set; } [DataMember] public string Name...

Remove resource wrapper from CakePHP REST API JSON

My question is similar to this one. I understand the answer given there. The OP of that question doesn't seem to have my issue. I am using CakePHP 2.2.3. I am fetching a resource like this: http://cakephpsite/lead_posts.json and it returns results like this: [ { "LeadPost": { "id": "1", "fieldA":...

What's the best way to map objects into ember model from REST Web API?

The topic of this post is: my solution is too slow for a large query return. I have a Web Api serving REST results like below from a call to localhost:9090/api/invetories?id=1: [ { "inventory_id": "1", "film_id": "1", "store_id": "1", "last_update": "2/15/2006 5:09:17 AM" }, { "inventory_id": "2", "film_id": "1", "store_id":...

Unable to upload file to Sharepoint @ Office 365 via REST

I'm having trouble creating/uploading files via Microsoft's REST API (or at least that's what they call it) for Sharepoint running on Office 365. It looks like I'm able to authenticate all right, but I'm getting 403 Forbidden when I try to create a file. The same user can upload a...

Using .update with nested Serializer to post Image

I have an ImageField. When I update it with the .update command, it does not properly save. It validates, returns a successful save, and says it is good. However, the image is never saved (I don't see it in my /media like I do my other pictures), and when it...

Spring Data Rest executes query but returns 500 internal Server Error

I am using spring boot and spring data rest and I am facing a 500 internal server error, but no messages are displayed in console. I have the following: public interface ProdutoVendaRepository extends PagingAndSortingRepository<ProdutoVenda, Integer> { @Query("SELECT new, SUM(i.valorMultiplicado)) FROM ProdutoVenda i JOIN i.produto o JOIN o.familia b...

Not able to hit 2nd services with generated Token

I have been provided with two services in which ist service is used for login purpose and it will return an xml node token which i to be added as the header in all other services call, In the attached sample code there are two functions in function CreateObject() i...

Sencha/Extjs rest call with all parameters

I'm using ExtJs 5.1.1 and I've written a simple view with a grid, and selecting one row the corresponding model property are editable in some text fields. When editing is completed the button 'save' call method, which use the rest proxy configured to write the changes on the server....

@RestController throws HTTP Status 406

I am working on a basic Hello World program using Spring and Restful webservices. But when I try to call my service I am getting below error message: HTTP Status 406 - description - The resource identified by this request is only capable of generating responses with characteristics not acceptable...

unable to resolve class in grails

I am developing a module in which some file need to be uploaded on a ftp server for that I have added the "commons-net-3.3.jar" in my grails app & while using it import import import import import It is throwing the error unable to resolve...

Render a controller into a String

I can render a template or a view into a String, but how can I render a controller into a String ? I would like to perform this kind of operation: def myAction = { ... def html = renderToString(controller: 'myController', action: 'myAction', params: [what:'ever']) render modify(html) ... } ...

Springboot REST application should accept and produce both XML and JSON

I am working on Springboot REST API. My application should consume and produce both XML and JSON. I came across the Jackson json Xml dependency. <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.5.4</version> </dependency> I added this in my pom.xml. Now I am able to accept xml input but the values are null when mapped...

How to specify supported http operation for a resource in json-ld?

I'm new to JSON-LD and I was wondering if there is any way of specifying supported operation of a resource in JSON-LD without using Hydra's supportedOperation or supportedProperty. Is there any way to specify the context something like : { "@context" : { "@vocab" : "", "data" : "object", "id"...

REST Jersey server JAX-RS 500 Internal Server Error

I'm calling this method and getting a 500 back from it. In the debugger I'm able to step though it all the way to the return statement at the end. No problem, r is populated as expected after is called, the status says 200 OK. But that's not what...

Groovy - timestamp from minutes

I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

Link to another resource in a REST API: by its ID, or by its URL?

I am creating some APIs using apiary, so the language used is JSON. Let's assume I need to represent this resource: { "id" : 9, "name" : "test", "customer_id" : 12, "user_id" : 1, "store_id" : 3, "notes" : "Lorem ipsum example long text" } Is it correct to refer...

REST api : correctly ask for an action

I'm currently working on a REST api. I've read a few times how to handle endpoints the right way, using the protocol (post, put, ...) to define which action should be made. Let's say I have a list of quotes. I have : a GET endpoint /quotes that let me...