开发者

Anonymous user count using Spring Security

I have managed to accomplish a couple features using Spring Security 3.0.5. The first is that I want a count and list of users that have a specific role. To accomplish this I instituted the HttpSession开发者_开发技巧EventPublisher and the spring configurations that go along with it. With these settings I can easily get the list of logged in users no matter what their privilege level - unless they are anonymous (ROLE_ANONYMOUS).

I'm using the anonymous tag in my security XML:

<security:anonymous />

I can debug the anonymous users coming in though AnonymousAuthenticationFilter.doFilter but the SessionRegistry.registerNewSession never gets called for these, most likely because there is no principal for anonymous users.

So I'm just looking for ideas. I would love to be able to list the count for the sessions that are anonymous, along with other registered users.


You can extend the AnonymousAuthenticationFilter and override the createAuthentication method (it's meant for overriding).

Then since this method is called only on a new anonymous authentication, whenever it's called you can increment a counter somewhere, or count them in any way convenient for you. You just need to count the calls to the method.


Here's an implementation of counting anonymous's in Spring Security.

public class ProxyAuthenticationFilter extends AnonymousAuthenticationFilter {

        private String key = "key";

        public ProxyAuthenticationFilter() {
            super(key);
        }

        public ProxyAuthenticationFilter(String key, Object principal, List<GrantedAuthority> authorities) {
    super(key, principal, authorities);
        }

        @Override
        protected Authentication createAuthentication(HttpServletRequest request) {

            // do increment and store somewhere 

            return super.createAuthentication(request);
        }
}


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.anonymous().authenticationFilter(proxyAuthenticationFilter());
        }

        @Bean
        protected ProxyAuthenticationFilter proxyAuthenticationFilter() {
            return new ProxyAuthenticationFilter();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜