2

我已经实现了 spring security oauth2 来保护不同的服务。

现在我需要记录客户端 ip、客户端 ID、请求服务、请求 URL 和事件类型,如“身份验证失败”、“授权失败”等。

我想出了以下

public class Events implements ApplicationListener<ApplicationEvent>{
private static Logger log = LoggerFactory.getLogger(Events.class);


@Override
public void onApplicationEvent(ApplicationEvent appEvent) {


    if (appEvent instanceof AuthenticationSuccessEvent) {
        AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;

        long  timestamp = event.getTimestamp();


        User user = (User) event.getAuthentication().getPrincipal();

        System.out.println("client " + user.getUsername() + " has been authenticated successfully.");

        UsernamePasswordAuthenticationToken source = (UsernamePasswordAuthenticationToken) event.getSource();


        WebAuthenticationDetails details = (WebAuthenticationDetails) source.getDetails();

        System.out.println("remote ip is " + details.getRemoteAddress());


    }

    if (appEvent instanceof AuthorizationFailureEvent) {
        //TODO
        ((AuthorizationFailureEvent) appEvent).getAccessDeniedException();
    }

    if (appEvent instanceof AbstractAuthenticationFailureEvent) {

        System.out.println("Sorry, authenticated for client " +  appEvent.getSource().toString() + " failure.");
    }
}

}

因为请求是异步的,所以我不知道如何从上下文中获取请求。如果我能得到 HttpServletRequest 请求,我几乎可以得到所有东西。

4

1 回答 1

0

参考这个。我在 web.xml 中添加了 RequestContextFilter。

<filter>

  <filter-name>requestContextFilter</filter-name>

  <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>

    <init-param>

      <param-name>threadContextInheritable</param-name>

      <param-value>true</param-value>

   </init-param>

</filter>

<filter-mapping>

  <filter-name>requestContextFilter</filter-name>

  <url-pattern>/*</url-pattern>

</filter-mapping>

它运作良好。

于 2015-09-23T01:24:37.947 回答