Java生成access token - GoEasy客户端安全

安装类库

pom.xml里添加jjwt

    <dependencies>
        ...
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
    </dependencies>

PubSub


    public String pubSubAccessToken(String id, String protectedChannel) {

        //应用的Secret key,登陆GoEasy->应用详情->Professional keys->Secret key
        String secretKey = "f7e4cf0f5c6db52d";

        //token的有效时间,最长不能超过3小时,为了安全,GoEasy不接受有效时间大于3小时的access token
        Date expirationTime = new Date(new Date().getTime() + TimeUnit.HOURS.toMillis(3));

        String accessToken = Jwts.builder()
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .claim("id", id)//发送方,必须与connect GoEasy时传入的id一致
                .claim("channel", protectedChannel)//接收方,授权的channel
                .claim("w", true)//写权限,是否允许发送(publish)
                .claim("r", true)//读权限,是否允许接收(subscriber)
                .setExpiration(expirationTime)
                .signWith(SignatureAlgorithm.HS256, secretKey.getBytes()).compact();

        return accessToken;
    }

IM

私聊


    public String privateChatAccessToken(String id, String toId) {

        //应用的Secret key,登陆GoEasy->应用详情->Professional keys->Secret key
        String secretKey = "f7e4cf0f5c6db52d";

        //token的有效时间,最长不能超过3小时,为了安全,GoEasy不接受有效时间大于3小时的access token
        Date expirationTime = new Date(new Date().getTime() + TimeUnit.HOURS.toMillis(3));

        String accessToken = Jwts.builder()
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .claim("id", id)//发送方,必须与connect GoEasy时传入的id一致
                .claim("to", toId)//接收方,私聊对象的id
                .claim("w", true)//写权限,是否允许发送
                .setExpiration(expirationTime)
                .signWith(SignatureAlgorithm.HS256, secretKey.getBytes()).compact();

        return accessToken;
    }

群聊



    public String groupChatAccessToken(String id, String... groupIds) {

        //应用的Secret key,登陆GoEasy->应用详情->Professional keys->Secret key
        String secretKey = "f7e4cf0f5c6db52d";

        //token的有效时间,最长不能超过3小时,为了安全,GoEasy不接受有效时间大于3小时的access token
        Date expirationTime = new Date(new Date().getTime() + TimeUnit.HOURS.toMillis(3));

        String accessToken = Jwts.builder()
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .claim("id", id)//必须与connect GoEasy时传入的id一致
                .claim("to", groupIds)//需要授权的groupId列表, 支持一次为多个群授权
                .claim("w", true)//写权限,是否允许发送
                .claim("r", true)//读权限,是否允许订阅(接收)
                .setExpiration(expirationTime)
                .signWith(SignatureAlgorithm.HS256, secretKey.getBytes()).compact();

        return accessToken;
    }

results matching ""

    No results matching ""