我知道 spring 安全性在成功进行身份验证时会创建一个 cookie 名称会话。是否有可能在 AuthenticationSuccessHandler 中获取该 cookie 值。
我有一个以下实现,我需要那个会话cookie值。我看起来像是HttpServletResponse的响应标头,但它们具有XSRF-TOKEN set-cookie标头,
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(
HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
// GET SESSION, COOKIE VALUE HERE
}
}
你能帮忙吗?
SESSION cookie 由 Spring Session 的DefaultCookieSerializer
创建,每次创建新会话时都会调用,不一定在身份验证成功后调用。
SpringSession 的SessionRepositoryFilter
包装 HttpServletRequest 的方式是,每当你在应用程序的任何时刻从请求中获取 HttpSession 时,你实际上都会得到一个 Spring Session 对象。但是,此 cookie 会在调用处理程序后写入响应,如SessionRepositoryFilter
所示:
try {
filterChain.doFilter(wrappedRequest, wrappedResponse);
}
finally {
wrappedRequest.commitSession(); //the SESSION cookie is created if necessary
}
因此,如果刚刚为此请求创建了会话...
- Cookie 在 HttpServletRequest 中不可用,因为 cookie 尚未发送(因此浏览器无法发送它) Cookie
- 不会将 HttpServletResponse 作为"Set-Cookie"标头,因为它将在应用程序处理完请求后写入。
但是,您可以获取 cookie 值:
String cookieValue = request.getSession().getId();
注意:上面的代码将强制Spring Session创建一个会话支持的Redis/Jdbc/etc,稍后将用于生成SESSION cookie。
我从请求中使用getSession().getId()
方法得到了它。我的例子是将 Webflux 实现与 Kotlin 一起使用,但显然在实现HttpServletRequest
类似,请参见 https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpServletRequest.html#getSession--
class AuthenticationSuccessHandler : ServerAuthenticationSuccessHandler {
private val location = URI.create("https://redirect.page")
private val redirectStrategy: ServerRedirectStrategy = DefaultServerRedirectStrategy()
override fun onAuthenticationSuccess(webFilterExchange: WebFilterExchange?, authentication: Authentication?): Mono<Void> {
val exchange = webFilterExchange!!.exchange
return exchange.session.flatMap {
it.id // 87b5639c-7404-48a1-b9da-3ca47691a962
this.redirectStrategy.sendRedirect(exchange, location)
}
}
}