Skip to content

Instantly share code, notes, and snippets.

@abhirockzz
Last active April 15, 2017 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhirockzz/1efed4c9674f7ad6333b867422a301c7 to your computer and use it in GitHub Desktop.
Save abhirockzz/1efed4c9674f7ad6333b867422a301c7 to your computer and use it in GitHub Desktop.
//custom Configurator implementation which maps (authenticated) user name to a token (sent via HTTP header)
public class TokenStore extends ServerEndpointConfig.Configurator {
Map<String, String> userTokens;
public TokenStore() {
userTokens = new ConcurrentHashMap<>();
}
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
String token = request.getHeaders().get("token").get(0);
String name = request.getUserPrincipal().getName();
userTokens.put(name, token);
}
public Map<String, String> getUserTokens(){
return Collections.unmodifiableMap(userTokens);
}
}
//the WebSocket (server) endpoint implementation which makes use of the token store
@ServerEndpoint(value = "/service/{id}",configurator = TokenStore.class)
public class BroadcastService {
private String token;
@OnOpen
public void test(@PathParam("id") String id, EndpointConfig cfg) { //injeted config by runtime
ServerEndpoint sCfg = (ServerEndpoint) cfg; //cast
TokenStore store = sCfg.getConfigurator(); //get custom implementation instance
token = cfgur.getUserTokens().get(id); //extract token and store as a member variable
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment