duanfan5012 2014-01-12 08:19
浏览 9
已采纳

如何在使用JS时隐藏pubnub键

I opened a ticket in pubnub and also read: https://help.pubnub.com/entries/22251291-Can-I-Hide-my-Application-Keys-

But I still can't understand how can I stop the user from seeing my keys as it is still on client side even after obfuscation.

What I want to do is something I read in this post: PubNub publish message between two Private Channels

  1. Create a public channel and a private the channel for each user
  2. Hide the keys from the user

I'm not sure how to create a private channel with custom keys that the user can't see.


EDIT: I was able to understand the flow of auth_key but can't find the php equivalency for the JS crypto lib to grant permission. any idea on how to implement it in PHP?

  • 写回答

2条回答 默认 最新

  • dousuie2222 2014-01-17 02:34
    关注

    Hiding Your API Keys with PubNub JS SDK

    With PubNub Access Manager you no longer need to worry about hiding your publish_key and subscribe_key in your source code in JavaScript or any other language! Typically you would consider that hiding your keys becomes a means to preventing access to streams of data on your PubNub Channels. However this is not necessary and there is a best practices method to use instead: The following is your solution for the new way to manage access and the new way to manage your keys.

    PubNub Access Manager Example JS/PHP Grant Revoke SDK

    You can issue per-user connection grant() and revoke() access in realtime on the PubNub global Real-Time Network. Various levels of security within the PubNub network using a grant/revoke (whitelist) permission scheme, where the first grant found in the hierarchy grants read/write access. Permissions are evaluated for both publish and subscribe based on this hierarchy. Our pam.php PubNub Access Manager PHP Class is finally ready to go! You can get started by seeing the example usage code below with full code coverage of the SDK. You can find all source code via the GitHub Gist Link:

    PubNub Access Manager (PAM) PHP Full Library for Granting and Revoking Access

    PubNub Access Manager (PAM) PHP Full Library for Granting and Revoking Access

    Include PAM and Initialize class access

    require('pam.php');
    
    $manager = new access(
        "pub-c-e132b7b4-0c2c-4d36-a828-1de1ea50d167",
        "sub-c-f95db694-6ff9-11e3-9291-02ee2ddab7fe",
        "sec-c-OWFkNWQ1NDctN2JiNy00NzJmLTk3Y2ItN2ExODZlYzkyNzY0"
    );
    

    Grant User Access

    Grant access to user with authkey of gZW5jb2RlZCBmaWx with read and write access for 5 minute ttl. You can make the authkey anything you want!

    print_r($manager->grant(
        "my_channel",        // CHANNEL
        "gZW5jb2RlZCBmaWx",  // STRING (AUTH KEY)
        true,                // READ
        true,                // WRITE
        5                    // TTL in MINUTES
    ));
    

    Grant User Presence Access

    Also grant access to the presence channel (required for PubNub Dev Console).

    print_r($manager->grant(
        "my_channel-pnpres", // CHANNEL
        "gZW5jb2RlZCBmaWx",  // STRING (AUTH KEY)
        true,                // READ
        true,                // WRITE
        5                    // TTL in MINUTES
    ));
    

    Grant GLOBAL Access (to all users)

    Exclude the authkey and you can global grant access to all.

    print_r($manager->grant_global(
        "my_channel", // CHANNEL
        true,         // READ
        true,         // WRITE
        5             // TTL in MINUTES
    ));
    

    Forever Grant Access

    You can grant access forever by setting the ttl param to 0.

    print_r($manager->grant_global(
        "my_channel", // CHANNEL
        true,         // READ
        true,         // WRITE
        0             // FOREVER GRANT!!!
    ));
    

    Revoke User Access

    Instantly revoke access to a user.

    print_r($manager->revoke(
        "some-other-channel", // CHANNEL
        "gZW5jb2RlZCBmaWx"    // STRING (AUTH KEY)
    ));
    

    Revoke Global Access

    You can also revoke Global Access by excluding the authkey param.

    print_r($manager->revoke(
        "some-other-channel" // CHANNEL
    ));
    

    PAM (PubNub Access Manager) PHP Class SDK pam.php

    The full file can be found here: PubNub Access Manager (PAM) PHP Full Library for Granting and Revoking Access

    <?php
    
    class access {
        function __construct( $pubkey, $subkey, $seckey ) {
            $this->publish_key   = $pubkey;
            $this->subscribe_key = $subkey;
            $this->secret_key    = $seckey;
        }
    
        function grant_global( $channel, $read=True, $write=True, $ttl=5 ) {
            /**  Grant GLOBAL Access on a Channel. **/
            return $this->_auth(array(
                "channel" => $channel,
                "r"       => $read  ? 1 : 0,
                "w"       => $write ? 1 : 0,
                "ttl"     => $ttl
            ));
        }
    
        function grant( $channel, $authkey=False, $read=True, $write=True, $ttl=5 ) {
            /**  Grant Access on a Channel. **/
            return $this->_auth(array(
                "channel" => $channel,
                "auth"    => $authkey,
                "r"       => $read  ? 1 : 0,
                "w"       => $write ? 1 : 0,
                "ttl"     => $ttl
            ));
        }
    
        function revoke( $channel, $authkey=False, $read=False, $write=False, $ttl=1 ) {
            /**  Revoke Access on a Channel.**/
            return $this->_auth(array(
                "channel" => $channel,
                "auth"    => $authkey,
                "r"       => $read  ? 1 : 0,
                "w"       => $write ? 1 : 0,
                "ttl"     => $ttl
            ));
        }
    
        function _sign($message) {
            /** Calculate a signature by secret key and message. **/
            return strtr( base64_encode(hash_hmac(
                'sha256',
                utf8_encode($message),
                utf8_encode($this->secret_key),
                true
            )), '+/', '-_' );
        }
    
        function _auth($query) { 
            /** Issue an authenticated request.**/
            if (!array_key_exists( 'timestamp', $query )) {
                $query['timestamp'] = time();
            }
    
            ## Global Grant?
            if ((array_key_exists('auth',$query)) && !$query['auth']) { 
                unset($query['auth']);
            }
    
            ## Construct String to Sign
            $params      = array();
            $sorted_keys = array_keys($query);
            sort($sorted_keys);
    
            foreach ($sorted_keys as $key) array_push(
                $params,
                $key . "=" . $query[$key]
            );
    
            $string_to_sign = 
                $this->subscribe_key . "
    " .
                $this->publish_key   . "
    " .
                "grant"              . "
    " .
                implode( "&", $params );
    
            $signature = $this->_sign($string_to_sign);
            $url       = (
                "https://pubsub.pubnub.com/v1/auth/grant/sub-key/" .
                $this->subscribe_key . "?" .
                implode( "&", $params ) .
                "&signature=" . $signature
            );
    
            $workspace_curl = curl_init();  
            curl_setopt( $workspace_curl, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt( $workspace_curl, CURLOPT_URL, $url );
            $result = curl_exec($workspace_curl);
            return $workspace_details =json_decode( $result, true );
        }
    }
    
    ?>
    

    pam.php: PubNub Access Manager (PAM) PHP Full Library for Granting and Revoking Access

    PubNub Dev Console Test Link:

    WARNING: PubNub Dev Console Requires Grant on Presence Channel too! You can set the presence access by granting on the suffix of -pnpres channel name.

    http://www.pubnub.com/console/?channel=my_channel&sub=sub-c-f95db694-6ff9-11e3-9291-02ee2ddab7fe&pub=pub-c-e132b7b4-0c2c-4d36-a828-1de1ea50d167&sec=sec-c-OWFkNWQ1NDctN2JiNy00NzJmLTk3Y2ItN2ExODZlYzkyNzY0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line