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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


two × = 14



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.