Registering specific request header using spring security events

In my grails app, failed login attempts are logged using spring security events as shown here http://grails-plugins.github.com/grails-spring-security-core/docs/manual/guide/single.html#7.3 % 20Registering% 20Callback% 20Closures

My problem is with finding the client ip. Usually, calling the getRemoteAddress function from the object object should do the job, but my case is that my application is behind a reverse proxy, so I have to get the ip from the X-Forwarded-For request header .

Neither the event object nor the private access application context parameters provide access to the request object. The global request object is also not available.

Any ideas on how to access the headers or any other way to implement this functionality?

+3


source to share


1 answer


You can get it from RequestContextHolder

if it exists:

GrailsWebRequest request = RequestContextHolder.currentRequestAttributes()
request.getHeader("X-Forwarded-For")

      

Generally, as you probably know, it is not a good idea to access your web session from Services. First of all, you are breaking abstraction and separation of service logic, and requests may not always be available or associated with the current thread. One way to access the session from the service is to encapsulate the HTTP session like this:

class WebUtilService {
    void withSession (Closure closure) {
        try {
            GrailsWebRequest request = RequestContextHolder.currentRequestAttributes()
            GrailsHttpSession session = request.session
            closure.call(session)
        }
        catch (IllegalStateException ise) {
            log.warn ("No WebRequest available!")
        }
    }
}

      



and you will use it like this:

class MyService {
    WebUtilService webUtilService

    void doSomething() {
        webUtilService.withSession { HttpSession session ->
            log.info(session.myValue)
            session.newValue = 'Possible, but should be exceptional'
        }
    }
}

      

where you can access the method getHeader()

.

Disclaimer: The code is from Marc-Oliver Scheele.

+2


source







All Articles