Last active
April 15, 2017 06:05
-
-
Save abhirockzz/1efed4c9674f7ad6333b867422a301c7 to your computer and use it in GitHub Desktop.
Managing state in WebSocket apps (see https://abhirockzz.wordpress.com/2017/04/15/handling-state-in-java-websocket-applications)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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