Home » Java » Enterprise Java » Spring Security: Prevent brute force attack

About Grygoriy Mykhalyuno

Grygoriy Mykhalyuno

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.

(0 rating, 0 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
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 our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
Email address:

Leave a Reply

1 Comment on "Spring Security: Prevent brute force attack"

newest oldest most voted
Notify of
Fahad Rafiq

Password crackers are using automated scripts to target websites to hack the passwords and Brute Force Attacks have become a common thing, but many don’t know the concept behind it and how these attacks are so successful at cracking the passwords of the websites.

The easiest method to block such attacks is by blacklisting the IPs that carry out such abuses, many hosting providers have added Brute Force Attacks protection in their added security features.

For more information about these attacks read: http://www.cloudways.com/blog/what-is-brute-force-attack/