我需要在成功验证用户之后在上下文中设置一些东西(更准确地说它是数据库上下文持有者)。我已正确配置弹簧安全性。凭据通过标头传递(但这里没关系)。 Sequent requestsa由SESSION ID扩充。
一切都很好,我只需要实现一些功能,在接受授权的请求后自动调用立即。
怎么做?
答案 0 :(得分:0)
当身份验证成功完成时,Spring Security将触发AuthenticationSuccessEvent
事件。您只需要注册一个事件监听器来监听该事件并提供一个回调,该回调将在此事件被触发后执行:
@Component
class SuccessfulAuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
// Put the function which is automatically invoked immediately
// after acceptance of the request as authorized.
}
}
为了拦截每个授权请求,只需注册一个普通过滤器并检查用户是否经过身份验证:
@Component
class AuthorizedRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
// do whatever is necessary
}
filterChain.doFilter(request, response);
}
}