使用 Spring 安全登录后如何做?

How to do something after the login with Spring Security?

我有一个 Spring 网络应用程序,它使用 Spring SAML 和 Spring 安全性来管理登录过程。 现在我需要在正确登录后执行一些任务。特别是我必须在 SecurityContext.getContext() 对象中存储一些数据。

我从未使用过 Spring Security/SAML,我不知道它如何管理来自 IdP 的 return。

代码中是否有任何地方通常可以在登录过程正确结束后放置代码?

我的意思是,我知道重定向页面的设置位置,但我无法将我的自定义代码放入此重定向页面的控制器中,因为该页面被多次访问,我需要 运行 我的仅在登录时自定义代码一次。

您在使用 Spring 的 Java 配置吗?

如果是这样,那么您的项目中可能有一个 class 覆盖 WebSecurityConfigurerAdapter。扩展此 class 可让您访问覆盖方法 configure(HttpSecurity http).

您可以使用提供的 HttpSecurity 构建器对象来配置很多东西,其中之一是身份验证成功处理程序。或多或少,您可以创建一个简单的 class 来实现 AuthenticationSuccessHandler(Spring 已经为扩展构建了一些 classes 以简化此操作),您可以调用 http.successHandler(yourSuccessHandler) 将其注册到 Spring 安全性。

实现该接口为您提供了将自定义代码放入 onAuthenticationSuccess( ... ) 方法的钩子。我想他们也有一个失败的。

您可以使用 AuthenticationSuccessEvent。只需注册一个实现 ApplicationListener 的 bean。

    @Component
    public class SomeSpringBean implements
                             ApplicationListener<AuthenticationSuccessEvent> {

        public onApplicationEvent(AuthenticationSuccessEvent event) {
           String userName = ((UserDetails) event.getAuthentication().
           //do stuff                                       
        }
   }

并且您需要注册 AuthenticationEventPublisher。 看这里:https://gist.github.com/msarhan/10834401

如果您使用自定义身份验证提供程序,您也可以在那里插入任何你想要的东西。

最好的方法是实现接口 SAMLUserDetailsService,它会自动将对象 return 从它的 loadUserBySAML 方法存储在 Authentication 对象中,您可以稍后查询来自 SecurityContext.getContext()。每次认证后都会调用一次该接口。有关详细信息和示例,请参阅 the manual

另一种可能性是AuthenticationSuccessHandler。登录过程调用 onAuthenticationSuccess 方法,该方法可以访问 Authentication 对象,该对象将存储在 SecurityContext.getContext().

只需创建您自己的 class 实现接口 AuthenticationSuccessHandler(您还可以扩展一些现有的 class,例如 SimpleUrlAuthenticationSuccessHandlerAbstractAuthenticationTargetUrlRequestHandler).然后通过更改现有 successRedirectHandler bean 中的 class 将您的实现插入 securityContext.xml

问题是,Authentication 对象往往是不可变的 - 因此第一种方法可能更好。