Version
spring-security 5.6.10
spring-websocket 5.3.27
Phenomenon
Implement websocket endpoint processor through AbstractWebSocketHandler.
Calling a method annotated with @PreAuthorize reports an error. Authentication information cannot be found in SecurityContext.
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException
An Authentication object was not found in the SecurityContext
reason
The thread calling websockethandler is not the user session thread, so there is no authentication information in the security context.
solve
Set the authentication information saved in the WebsocketSession to the SecurityContext when processing the message
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
public class MyWsHandler extends AbstractWebSocketHandler {
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
// 在安全上下文中设置认证信息
SecurityContextHolder.getContext().setAuthentication((Authentication)session.getPrincipal());
super.handleMessage(session, message);
}
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 调用受保护的方法
this.service.doSomething();
}
}