Spring Security: Prevent brute force attack

Spring Security can do lot of stuff for you.

Account blocking, password salt. But what about brute force blocker.

That what you have to do by yourself.

Fortunately Spring is quite flexible framework so it is not a big deal to configure it.

Let me show you little guide how to do this for Grails application.

First of all you have to enable springSecurityEventListener in your config.groovy

grails.plugins.springsecurity.useSecurityEventListener = true

then implement listeners
in /src/bruteforce create classes

Registers all failed attempts to login. Main purpose to count attempts for particular account ant block user

class AuthenticationFailureListener implements ApplicationListener {

    LoginAttemptCacheService loginAttemptCacheService

    void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {

next we have to create listener for successful logins
in same package

 Listener for successfull logins. Used for reseting number on unsuccessfull logins for specific account
class AuthenticationSuccessEventListener implements ApplicationListener{

    LoginAttemptCacheService loginAttemptCacheService

    void onApplicationEvent(AuthenticationSuccessEvent e) {

We were not putting them in our grails-app folder so we need to regiter these classes as spring beans.
Add next lines into grails-app/conf/spring/resources.groovy

beans = {
    authenticationFailureListener(AuthenticationFailureListener) {
        loginAttemptCacheService = ref('loginAttemptCacheService')

    authenticationSuccessEventListener(AuthenticationSuccessEventListener) {
        loginAttemptCacheService = ref('loginAttemptCacheService')

You probably notice usage of LoginAttemptCacheService loginAttemptCacheService
Let’s implement it. This would be typical grails service

package com.picsel.officeanywhere

import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache

import java.util.concurrent.TimeUnit
import org.apache.commons.lang.math.NumberUtils
import javax.annotation.PostConstruct

class LoginAttemptCacheService {

    private LoadingCache
    private int allowedNumberOfAttempts
    def grailsApplication

    void init() {
        allowedNumberOfAttempts = grailsApplication.config.brutforce.loginAttempts.allowedNumberOfAttempts
        int time = grailsApplication.config.brutforce.loginAttempts.time

        log.info 'account block configured for $time minutes'
        attempts = CacheBuilder.newBuilder()
                   .expireAfterWrite(time, TimeUnit.MINUTES)
                   .build({0} as CacheLoader);

     * Triggers on each unsuccessful login attempt and increases number of attempts in local accumulator
     * @param login - username which is trying to login
     * @return
    def failLogin(String login) {
        def numberOfAttempts = attempts.get(login)
        log.debug 'fail login $login previous number for attempts $numberOfAttempts'

        if (numberOfAttempts > allowedNumberOfAttempts) {
        } else {
            attempts.put(login, numberOfAttempts)

     * Triggers on each successful login attempt and resets number of attempts in local accumulator
     * @param login - username which is login
    def loginSuccess(String login) {
        log.debug 'successfull login for $login'

     * Disable user account so it would not able to login
     * @param login - username that has to be disabled
    private void blockUser(String login) {
        log.debug 'blocking user: $login'
        def user = User.findByUsername(login)
        if (user) {
            user.accountLocked = true;
            user.save(flush: true)

We will be using CacheBuilder from google guava library. So add next line to BuildConfig.groovy

    dependencies {
        runtime 'com.google.guava:guava:11.0.1'

And the last step add service configuration to cinfig.groovy

brutforce {
    loginAttempts {
        time = 5
        allowedNumberOfAttempts = 3

That’s it, you ready to run you application.
For typical java project almost everething will be the same. Same listeners and same services.

More about Spring Security Events
More about caching with google guava

Grails user can simple use this plugin https://github.com/grygoriy/bruteforcedefender

Happy coding and don’t forget to share!

Reference: Prevent brute force attack with Spring Security from our JCG partner Grygoriy Mykhalyuno at the Grygoriy Mykhalyuno’s blog blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Leave a Reply

6 − six =

Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: