让我先说明我的方案应拒绝访问 。使用Spring Security 4内置Spring Boot 4.我允许任何人连接到websocket并订阅一个主题,但我确保能够使用以下Web套接字安全配置向主题发送消息:
@Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.simpSubscribeDestMatchers("/main-page-feed/thought-queue/**").permitAll()
.simpDestMatchers("/thought-bubble/push-to-queue/**").authenticated();
}
@Override
protected boolean sameOriginDisabled() {
return true;
}
}
因此,当您尝试在未经身份验证时向/thought-bubble/push-to-queue
发送消息时,它会拒绝您(正确,我想强调这一点,因为我可以在此找到其他唯一的问题是异常被错误抛出的时候)并抛出AccessDeniedException
。我不理解的是,与websocket安全性相反,Spring HTTP安全性会锁定某些内容并拒绝访问,它不会抛出异常,它只是发送HTTP状态。我尝试使用@ExceptionHandler
,AccessDenied处理程序,但我尝试过的任何东西都无法捕获并处理此异常。下面是堆栈跟踪和其他相关文件,任何想法都很受欢迎,因为我很困难。我已经尝试在调试中单步执行源代码,但我并没有真正看到问题所在。
堆栈追踪:
org.springframework.messaging.MessageDeliveryException: Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:127) ~[spring-messaging-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:104) ~[spring-messaging-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.messaging.StompSubProtocolHandler.handleMessageFromClient(StompSubProtocolHandler.java:298) ~[spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.handleMessage(SubProtocolWebSocketHandler.java:307) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.handleMessage(WebSocketHandlerDecorator.java:75) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.handleMessage(LoggingWebSocketHandlerDecorator.java:56) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.handleMessage(ExceptionWebSocketHandlerDecorator.java:58) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.sockjs.transport.session.AbstractSockJsSession.delegateMessages(AbstractSockJsSession.java:382) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession.handleMessage(WebSocketServerSockJsSession.java:193) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.sockjs.transport.handler.SockJsWebSocketHandler.handleTextMessage(SockJsWebSocketHandler.java:92) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.handler.AbstractWebSocketHandler.handleMessage(AbstractWebSocketHandler.java:43) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleTextMessage(StandardWebSocketHandlerAdapter.java:110) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$000(StandardWebSocketHandlerAdapter.java:42) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:81) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:78) [spring-websocket-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:399) [tomcat-embed-websocket-8.5.6.jar:8.5.6]
at org.apache.tomcat.websocket.server.WsFrameServer.sendMessageText(WsFrameServer.java:106) [tomcat-embed-websocket-8.5.6.jar:8.5.6]
at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:500) [tomcat-embed-websocket-8.5.6.jar:8.5.6]
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:295) [tomcat-embed-websocket-8.5.6.jar:8.5.6]
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:131) [tomcat-embed-websocket-8.5.6.jar:8.5.6]
at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:69) [tomcat-embed-websocket-8.5.6.jar:8.5.6]
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:148) [tomcat-embed-websocket-8.5.6.jar:8.5.6]
at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:54) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:53) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410) [tomcat-embed-core-8.5.6.jar:8.5.6]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.6.jar:8.5.6]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_101]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_101]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.6.jar:8.5.6]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_101]
Caused by: org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.security.messaging.access.intercept.ChannelSecurityInterceptor.preSend(ChannelSecurityInterceptor.java:71) ~[spring-security-messaging-4.0.2.RELEASE.jar:4.0.2.RELEASE]
at org.springframework.messaging.support.AbstractMessageChannel$ChannelInterceptorChain.applyPreSend(AbstractMessageChannel.java:158) ~[spring-messaging-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:113) ~[spring-messaging-4.3.5.RELEASE.jar:4.3.5.RELEASE]
... 30 common frames omitted
安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserProfileService userProfileService;
@Autowired
private CustomAccessDeniedHandler accessDeniedHandler;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userProfileService);
auth.authenticationProvider(authenticationProvider());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userProfileService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/javascript/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http .httpBasic()
.and()
.authorizeRequests()
.antMatchers("/", "/index.html", "/home.html", "/getLatestPost", "/application-socket-conn/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler).and()
.csrf().disable();
}
}
Web Socket配置:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
//Javascript connection subscribes to this URI
config.enableSimpleBroker("/main-page-feed");
//STOMP messages are sent to this URI + suffix
config.setApplicationDestinationPrefixes("/thought-bubble");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//URI used for SockJS connection
registry.addEndpoint("/application-socket-conn").withSockJS();
}
}
自定义AccessDenied处理程序(没有捕获它):
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Autowired
@Qualifier("clientOutboundChannel")
private MessageChannel clientOutboundChannel;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
Message<String> message = new Message<String>() {
@Override
public String getPayload() {
return "Access denied.";
}
@Override
public MessageHeaders getHeaders() {
return null;
}
};
clientOutboundChannel.send(message);
}
}
Web套接字控制器
@RestController
public class WebSocketController {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@MessageMapping("/push-to-queue")
public void pushThoughtToQueue(@Payload ThoughtEntity entity) throws Exception {
Date today = new Date(Calendar.getInstance().getTimeInMillis());
entity.setPostDate(today);
entity.setFavoriteCount(0);
this.simpMessagingTemplate.convertAndSend("/main-page-feed/thought-queue", entity);
}
}
我认为AffirmativeBased
是引发它的类,但是我不确定为什么,或者为什么普通(非web套接字)spring安全性在拒绝访问某些内容时不会这样做。就像我说的那样,它正确地拒绝访问,但它抛出了运行时异常,并通过websocket将丑陋的堆栈跟踪发送回客户端。
更新:
我已经意识到无论用户是否登录都会抛出异常,因此我认为这是一个不同的问题。就像我说的那样,我没有在这个应用程序中使用ROLE
,我认为这与它有关。我目前正在研究匿名角色,因为我认为这与正在发生的事情有关。
答案 0 :(得分:1)
似乎您的websocket客户端代码没有发送授权信息。通常默认情况下不处理它,您应该创建自己的方式来连接安全性。
在我的情况下,我使用oauth授权,并且必须指定在stompClient连接期间指定的特定标头Authorization : Bearer _uuid_token_
。
看看这个片段以获得一般的想法。 (我正在使用AngularJS)
(function() {
'use strict';
/* globals SockJS, Stomp */
angular
.module('myApp')
.factory('global_WebSocket', GlobalWebSocketClient);
GlobalWebSocketClient.$inject = ['$window', 'localStorageService', '$q'];
function GlobalWebSocketClient($window, localStorageService, $q) {
var connected = $q.defer();
var established = {established: false} ;
var loc = $window.location;
var url = loc.protocol + '//' + loc.host + loc.pathname + 'websocket';
var token = localStorageService.get('token');
if (token && token.expires_at && token.expires_at > new Date().getTime()) {
url += '?access_token=' + token.access_token;
} else {
url += '?access_token=no token';
}
/*jshint camelcase: false */
var socket = new SockJS(url);
/*jshint camelcase: false */
var stompClient = Stomp.over(socket);
var headers = {
Authorization : 'Bearer ' + token.access_token,
};
stompClient.debug = null;
var establishConnection = function() {
stompClient.connect(headers, function() {
established.established = true;
connected.resolve('success');
}, function(error) {
console.log("ERROR CONNECTNG!");
console.log(error.headers);
establishConnection();
});
};
establishConnection();
return {
connected: connected,
client: stompClient,
established: established
};
}
})();
正如您所看到的,此代码构造了url添加access_token以及指定授权标头,这些标头已在之前建立并存储在localStorageService
中。我猜你假设你的客户端默认发送标题,但是sockjs并非如此。
然后我可以创建这样的客户服务
(function() {
'use strict';
/* globals SockJS, Stomp */
angular
.module('myApp')
.factory('synchronization_Status', SynchronizationFileTrackerService);
SynchronizationFileTrackerService.$inject = ['global_WebSocket'];
function SynchronizationFileTrackerService (global_WebSocket) {
var stompClient = global_WebSocket;
var subscriber = {} ;
return {
subscribe: subscribe,
unsubscribe: unsubscribe
};
function unsubscribe(target) {
if (subscriber[target]) {
subscriber[target].unsubscribe();
}
};
function subscribe(forTarget, handler) {
if (stompClient.established.established) {
subscriber[forTarget] = stompClient.client.subscribe('/synchronization/status/' + forTarget, function(data) {
data = angular.fromJson(data.body);
handler(angular.fromJson(data));
});
} else {
stompClient.connected.promise.then(
function() {
subscriber[forTarget] = stompClient.client.subscribe('/synchronization/status/' + forTarget, function(data) {
data = angular.fromJson(data.body);
handler(angular.fromJson(data));
});
}, null, null);
}
}
}
})();
在我的UI代码中重用这样的服务就像:
synchronization_Status.subscribe(ctrl.id, funciton(response){ctrl.currentStatus = response} );