我目前正在开发一个spring启动应用程序,并且我有一个处理程序,它将HttpServletRequest作为参数。我想知道,是否有可能调用一个bean -提供会话cookie -可以返回谁发出请求的信息?(如用户名)
最后,我找到了使代码按预期方式工作的方法。
package org.my.package;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY;
@Slf4j
@Configuration
public class CsrfDeniedHandlerConfig {
@AllArgsConstructor
static class CsrfDeniedHandler implements AccessDeniedHandler {
private final AccessDeniedHandler accessDeniedHandler;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (accessDeniedException.getClass().equals(InvalidCsrfTokenException.class)) {
SecurityContextImpl securityContext = (SecurityContextImpl) request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY);
User user = (User) securityContext.getAuthentication().getPrincipal();
log.error("Invalid CSRF token request from {}: {}", user.getUsername().toUpperCase(), accessDeniedException.getMessage());
}
accessDeniedHandler.handle(request, response, accessDeniedException);
}
}
@Bean
public AccessDeniedHandler csrfDeniedHandler() {
return new CsrfDeniedHandler(new AccessDeniedHandlerImpl());
}
}