Spring Security + WebSocket——@MessageMapping中Authentication为NULL解决方案之一

问题描述 

2020-08-06 15:55:53.988 ERROR 29260 --- [boundChannel-17] .WebSocketAnnotationMethodMessageHandler : Unhandled exception from message handler method

java.lang.NullPointerException: null
	at cn.edu.zstu.shihua.xihu.controller.WebSocketController.handleMsg(WebSocketController.java:33) ~[classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
	at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:171) ~[spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE]
	at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:120) ~[spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE]
	at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMatch(AbstractMethodMessageHandler.java:565) [spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE]
	at org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.handleMatch(SimpAnnotationMethodMessageHandler.java:511) [spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE]
	at org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.handleMatch(SimpAnnotationMethodMessageHandler.java:94) [spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE]
	at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessageInternal(AbstractMethodMessageHandler.java:520) [spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE]
	at org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessage(AbstractMethodMessageHandler.java:454) [spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE]
	at org.springframework.messaging.support.ExecutorSubscribableChannel$SendTask.run(ExecutorSubscribableChannel.java:144) [spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_181]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_181]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]

解决方案

在自定义的Spring Security 配置CustomWebSecurityConfig extends WebSecurityConfigurerAdapter 中删除相关路径

 

参考文章

Websocket Authentication and Authorization in Spring

SecurityContextHolder.getContext().getAuthentication()为null的问题