Search in sources :

Example 1 with IpMessagingGrant

use of com.twilio.jwt.accesstoken.IpMessagingGrant in project api-snippets by TwilioDevEd.

the class WebApp method main.

public static void main(String[] args) {
    // Serve static files from src/main/resources/public
    staticFileLocation("/public");
    // Create a Faker instance to generate a random username for the connecting user
    Faker faker = new Faker();
    // Create an access token using our Twilio credentials
    get("/token", "application/json", (request, response) -> {
        // Generate a random username for the connecting client
        String identity = faker.name().firstName() + faker.name().lastName() + faker.address().zipCode();
        // Create an endpoint ID which uniquely identifies the user on their current device
        String appName = "TwilioChatDemo";
        String endpointId = appName + ":" + identity + ":" + request.params("device");
        // Fetch environment info
        Map<String, String> env = new HashMap<String, String>();
        Path path = Paths.get(".env");
        Files.lines(path).forEach(s -> {
            String[] keyVal = s.split("=");
            String key = keyVal[0];
            String val = keyVal[1];
            env.put(key, val);
        });
        // Create IP messaging grant
        IpMessagingGrant grant = new IpMessagingGrant();
        grant.setEndpointId(endpointId);
        grant.setServiceSid(env.get("TWILIO_IPM_SERVICE_SID"));
        // Create access token
        AccessToken token = new AccessToken.Builder(System.getenv("TWILIO_ACCOUNT_SID"), System.getenv("TWILIO_API_KEY"), System.getenv("TWILIO_API_SECRET")).identity(identity).grant(grant).build();
        // create JSON response payload
        HashMap<String, String> json = new HashMap<String, String>();
        json.put("identity", identity);
        json.put("token", token.toJwt());
        // Render JSON response
        Gson gson = new Gson();
        return gson.toJson(json);
    });
}
Also used : Path(java.nio.file.Path) IpMessagingGrant(com.twilio.jwt.accesstoken.IpMessagingGrant) Faker(com.github.javafaker.Faker) HashMap(java.util.HashMap) AccessToken(com.twilio.jwt.accesstoken.AccessToken) Gson(com.google.gson.Gson)

Aggregations

Faker (com.github.javafaker.Faker)1 Gson (com.google.gson.Gson)1 AccessToken (com.twilio.jwt.accesstoken.AccessToken)1 IpMessagingGrant (com.twilio.jwt.accesstoken.IpMessagingGrant)1 Path (java.nio.file.Path)1 HashMap (java.util.HashMap)1