【问题标题】:Store IP address in UserDetails instance在 UserDetails 实例中存储 IP 地址
【发布时间】:2014-05-23 23:49:08
【问题描述】:

在我的 Web 应用程序中,我使用 Spring Security 和 UserDetailsService 实现进行身份验证。

现在我需要获取当前会话的客户端 IP 地址并将其存储在某处,我想将其存储在 UserDetails 实例中,以便在我需要的地方检索它。

实现这一目标的正确方法是什么? Spring MVC/Security 中是否有任何工具可以在服务层获取 IP 地址?

注意如果客户端未通过身份验证,我还需要知道 IP 地址(以记录访问尝试)

【问题讨论】:

标签: java spring spring-mvc spring-security


【解决方案1】:

IP 地址已经存在于Authentication 对象中(不是UserDetails)。

您可以在Authentication 对象上调用getDetails(),在Web 应用程序和正确配置的Spring Security 环境中,这将为您提供一个WebAuthenticationDetails 实例,其中包含IP 地址。可以调用getRemoteAddress方法获取地址。 (见javadoc)..

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
String ipAddress = details.getRemoteAddress();

沿着这些思路,你可以把它放在一个实用方法或其他东西后面来获取 IP 地址。

显然您想记录身份验证尝试,这可以通过实现ApplicationListener 并让它监听AbstractAuthenticationEvents 来轻松实现。 Spring Security 为每次身份验证尝试发出这些,并且还将Authentication(包含IP地址)包含在其中。

public class AuthenticationAttemptLoggerListener implements ApplicationListener<AbstractAuthenticationEvent> {

    private final Logger logger = LoggerFactory.getLogger(AuthenticationAttemptLoggerListener.class);

    public void onApplicationEvent(AbstractAuthenticationEvent event) {
        Authentication auth = event.getAuthentication();
        WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
        String ipAddress = details.getRemoteAddress();

        if (event instanceof AbstractAuthenticationFailureEvent) {
            logger.warn("Unsuccesful authentication attemped from: {}", ipAddress);
        } else {
            logger.info("Succesful authentication attemped from: {}", ipAddress);
        }
    }
}

这样的东西应该可以捕获并记录所有内容。你可能想看看所有的available events

【讨论】:

  • 如果客户端未通过身份验证,我还需要知道 IP 地址(以记录访问尝试)
  • 应该始终设置详细信息,这些是在身份验证实际发生之前设置的(检查UsernamePasswordAuthenticationFilter 的来源。如果您想记录尝试,只需创建一个侦听@的ApplicationListener 987654339@ 或者如果您想要所有事件 AbstractAuthenticationEvent 然后只需从 Authentication 对象中检索它。
猜你喜欢
  • 2014-09-14
  • 1970-01-01
  • 2011-10-05
  • 2020-06-11
  • 1970-01-01
  • 2022-07-29
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多