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

    @Override
    void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
        loginAttemptCacheService.failLogin(e.authentication.name)
    }
}

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

    @Override
    void onApplicationEvent(AuthenticationSuccessEvent e) {
        loginAttemptCacheService.loginSuccess(e.authentication.name)
    }
}

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
               attempts;
    private int allowedNumberOfAttempts
    def grailsApplication

    @PostConstruct
    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'
        numberOfAttempts++

        if (numberOfAttempts > allowedNumberOfAttempts) {
            blockUser(login)
            attempts.invalidate(login)
        } 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'
        attempts.invalidate(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!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


7 − three =



Java Code Geeks and all content copyright © 2010-2014, 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:
Close