Reputation: 1953
I am implementing spring web socket into our web application and I want to access the user name in the socket controller method but I am getting it as null.
Here is the code
@MessageMapping("/user/sockettest" )
@SendTo("/topic/sockettestresult")
public String sockAdd(ListId[] listIds) {
..
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return stringRet;
}
The spring-security xml looks like this
<sec:intercept-url pattern="/topic/**" access="permitAll" />
<sec:intercept-url pattern="/" access="permitAll" />
<sec:intercept-url pattern="/login*" access="permitAll" />
<sec:intercept-url pattern="/resources/**" access="permitAll" />
<sec:form-login login-page="/login" default-target-url="/user/home" always-use-default-target="true" authentication-failure-url="/login?error"/>
<sec:logout logout-success-url="/login?logout" delete-cookies="JSESSIONID" />
<sec:access-denied-handler error-page="/denied"/>
<sec:intercept-url pattern="denied/*" access="permitAll" />
<sec:csrf disabled="true" />
</sec:http>
The socket configuration looks like this
<websocket:stomp-endpoint path="/user/sockettest">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
<websocket:message-converters register-defaults="false">
<bean id="mappingJackson2MessageConverter" class="org.springframework.messaging.converter.MappingJackson2MessageConverter">
<property name="objectMapper" ref="objectMapper"></property>
</bean>
</websocket:message-converters>
</websocket:message-broker>
I have looked at some examples and most of them are in java config, however the problem that I have with that is that when I use java config, it is adding an extra /info to the destination url and it is not even connecting to the socket so I am taking the xml route.
I am pretty new to spring web sockets and I am thinking that I am missing something while integrating it with spring security but that's just me. Let me know what I am doing wrong here?
Upvotes: 3
Views: 1315
Reputation: 533
You can access current user by adding java.security.Principal
parameter to socket controller method.
@MessageMapping("/user/sockettest" )
@SendTo("/topic/sockettestresult")
public String sockAdd(ListId[] listIds, Principal principal) {
//do whatever you want
return stringRet;
}
Upvotes: 5