我已经实现了 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 请求,我几乎可以得到所有东西。