16

I'm doing experiments with Spring 4 websockets and stomp, and I have a hard time figuring out how to get/set the current user and other session attributes in a message handling method annotated with @MessageMapping.

The documentation says that the message handling methods can take a Principal as argument, and I found that the principal is retrieved by Spring by calling getUserPrincipal() on the native socket session, and then associated with the socket session, but I haven't found any way to easily customize this behavior, other than writing a servlet filter and wrap the original request into a wrapper returning the principal found in my cookie.

So my questions are:

  1. How to manually set the principal to the socket session, when the client connects (I have this information thanks to a custom cookie, and I don't use Spring security)?
  2. If 1 is not possible, how to add additional attributes to the socket session when the client connects?
  3. How to access the socket session and its attributes from a message handling method?
  4. Is there a way to access the login and passcode sent by the browser at connection time. They seem to be completely ignore by Spring and not accessible.
4

2 回答 2

7

更新:使用 Spring 4.1,可以将用户设置为从上面的 #1 握手。根据Spring 文档,您可以创建一个扩展 DefaultHandshakeHandler 的新类并覆盖 determineUser 方法。此外,如果您有令牌,您还可以创建一个设置主体的安全过滤器。我自己实现了第二个,并在下面包含了一些示例代码。

对于#2 和#3,我认为这仍然是不可能的。对于 #4 Spring 故意忽略这些文档 here

DefaultHandshakeHandler 子类的示例代码:

@Configuration
@EnableWebSocketMessageBroker
public class ApplicationWebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {

    public class MyHandshakeHandler extends DefaultHandshakeHandler {

        @Override
        protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, 
                                          Map<String, Object> attributes) {
            // add your own code to determine the user
            return null;
        }
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        registry.addEndpoint("/myEndPoint").setHandshakeHandler(new MyHandshakeHandler());

    }
}

安全过滤器的示例代码:

public class ApplicationSecurityTokenFilter extends GenericFilterBean {

    private final static String AUTHENTICATION_PARAMETER = "authentication";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            // check to see if already authenticated before trying again
            Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
            if ((existingAuth == null) || !existingAuth.isAuthenticated()) {
                HttpServletRequest request = (HttpServletRequest)servletRequest;
                UsernamePasswordAuthenticationToken token = extractToken(request);
                // dump token into security context (for authentication-provider to pick up)
                if (token != null) {  // if it exists
                    SecurityContextHolder.getContext().setAuthentication(token);
                }
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    private UsernamePasswordAuthenticationToken extractToken( HttpServletRequest request ) {
        UsernamePasswordAuthenticationToken authenticationToken = null;
        // do what you need to extract the information for a token
        // in this example we assume a query string that has an authenticate
        // parameter with a "user:password" string.  A new UsernamePasswordAuthenticationToken
        // is created and then normal authentication happens using this info.
        // This is just a sample and I am sure there are more secure ways to do this.
        if (request.getQueryString() != null) {
            String[] pairs = request.getQueryString().split("&");
            for (String pair : pairs) {
                String[] pairTokens = pair.split("=");
                if (pairTokens.length == 2) {
                    if (AUTHENTICATION_PARAMETER.equals(pairTokens[0])) {
                        String[] tokens = pairTokens[1].split(":");
                        if (tokens.length == 2) {
                            log.debug("Using credentials: " + pairTokens[1]);
                            authenticationToken = new UsernamePasswordAuthenticationToken(tokens[0], tokens[1]);
                        }
                    }
                }
            }
        }
        return authenticationToken;
    }
}

// set up your web security for the area in question
@Configuration
public class SubscriptionWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().antMatchers("/myEndPoint**","/myEndPoint/**").and()
                .addFilterBefore(new ApplicationSecurityTokenFilter(), UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic()  // leave this if you want non web browser clients to connect and add an auth header
                .and()
                .csrf().disable();
    }
}

**注意: ** 不要将您的过滤器声明为 Bean。如果你这样做了,那么它也会在通用过滤器中被拾取(至少使用 Spring Boot),所以它会在每个请求上触发。

于 2015-07-20T13:51:37.973 回答
4

这暂时是不可能的(Spring 4.0)。Spring 已打开(并考虑)一个问题:https ://jira.springsource.org/browse/SPR-11228

于 2014-01-15T15:57:31.437 回答