Set up JSAPI authentication

更新时间:
复制 MD 格式

Restrict which web pages can call which JavaScript APIs (JSAPIs) in the mPaaS H5 container by implementing a custom access control provider.

By default, any page loaded in the H5 container can invoke any JSAPI. Implementing H5JSApiPermissionProvider lets you gate each JSAPI call by URL domain and scheme before it executes.

Procedure

  1. Implement a custom access control provider. Create a class that implements H5JSApiPermissionProvider and override its two methods:

    public class H5JSApiPermissionProviderImpl implements H5JSApiPermissionProvider {
        @Override
        public boolean hasDomainPermission(String jsapi, String url) {
            // Called for every JSAPI request. Return true to allow, false to deny.
            // Always check jsapi, url, and uri for null before use to avoid NullPointerException.
            Uri uri = Uri.parse(url);
            String domain = uri.getHost();
            String scheme = uri.getScheme();
            if (!TextUtils.isEmpty(domain) && domain.equals("www.example.com") && "https".equals(scheme)) {
                return true;
            } else {
                return false;
            }
        }
    
        @Override
        public boolean hasThisPermission(String jsapi, String url) {
            // Controls JSAPI-level permission regardless of URL.
            // Return false to defer all per-JSAPI decisions to hasDomainPermission.
            return false;
        }
    }

    Method reference:

    Method

    Parameters

    Return value

    hasDomainPermission(String jsapi, String url)

    jsapi: JSAPI name being called; url: URL of the calling page

    true to allow the call; false to deny it

    hasThisPermission(String jsapi, String url)

    Same as above

    true to grant permission at the JSAPI level, bypassing domain checks; false to rely on hasDomainPermission

    Important

    Match URLs precisely. Always check at minimum the URI scheme and host. Avoid imprecise string methods such as contains, startsWith, endsWith, and indexOf. Use regular expressions only if you can guarantee they are anchored and unambiguous.

  2. Register the provider. Call setProvider after mPaaS initializes and before the H5 container launches.

    H5Utils.setProvider(H5JSApiPermissionProvider.class.getName(), new H5JSApiPermissionProviderImpl());