### Example: Starting SMS Authentication - Java Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_api_primary_sms_auth An example demonstrating how to initiate SMS primary authentication in Java. It sets up the server URL and phone number and then calls the SDK method. This code snippet assumes the SFUemSDK instance is available. ```java public startSMSAuth() { let url = "https://10.244.3.23"; let phoneNumber = "86-185xxxxxx8626@sms"; SFUemSDK.getInstance().startPrimarySmsAuth(url, phoneNumber); } ``` -------------------------------- ### Initialize and Unregister SDK Event Listener (TypeScript) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_demo_introduce Demonstrates the initialization of the SDK within an application's entry point. This code is part of the main Demo application and handles the initial setup for SDK functionalities. It is crucial for starting any SDK-related operations. ```typescript export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { /** * SDK初始化 */ this.init(); } } ``` -------------------------------- ### Subordinate Application Configuration (plist) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_demo_introduce Configuration for a subordinate application in a master-sub application setup. It requires a URL scheme in `Info.plist` in the format `SFEasyApp.` (where `bundleId` is the subordinate app's package name) for the main app to launch it after authorization. Additionally, the main app's URL scheme must be added to the subordinate app's `LSApplicationQueriesSchemes` whitelist to check if the main app is installed. ```xml CFBundleTypeRole Editor CFBundleURLSchemes SFEasyApp.com.sangfor.sdktestsubapp ``` ```xml SFEasyApp.com.sangfor.sdktest ``` -------------------------------- ### POST /initSDK Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_api_initialize Initializes the SDK to start and configure its services. This method must be called before any other SDK operations and should only be invoked within didFinishLaunchingWithOptions on the main thread. ```APIDOC ## POST /initSDK ### Description Used to launch and initialize the SDK. This must be called before other API calls and should only be invoked in didFinishLaunchingWithOptions on the main thread. ### Method POST ### Endpoint /initSDK ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sdkMode** (SFSDKMode) - Required - SDK mode option. - **sdkFlags** (SFSDKFlags) - Required - SDK basic configuration options. - **extra** (NSDictionary *) - Optional - Extra SDK configurations, key-value reference in Table 4. ### Request Example ```objective-c [[SFUemSDK sharedInstance] initSDK:SFSDKModeSupporVpnSandbox flags:SFSDKFlagsHostApplication | SFSDKFlagsVpnModeTcp extra:nil]; ``` ### Response #### Success Response (200) This endpoint does not return a specific success response body, but successful initialization is indicated by the absence of errors. #### Response Example None ### Notes 1. This interface is used to start and initialize the SDK. It must be called before calling other interfaces and can only be called in didFinishLaunchingWithOptions. 2. The initialization method must be called on the main thread. ### SFSDKMode Options: - **SFSDKModeSupportMutable**: SDK startup mode changes according to configuration (Recommended). - **SFSDKModeSupportVpn**: SDK enables VPN access function (Deprecated, not recommended). - **SFSDKModeSupportVpnSandbox**: SDK launches VPN and secure sandbox functions (Deprecated, not recommended). **SFSDKModeSupportMutable Description:** Used when some users of the app integrating the SDK should only have the ability to access internal network services via proxy, while others should have both proxy access and data leakage prevention capabilities. **Authorization Occupancy:** 1. When the app integrating the SDK is authorized to a user in the App Center, the user runs in access + secure sandbox mode, occupying concurrent authorization and UEM mobile authorization. 2. When the app integrating the SDK is not authorized to a user in the App Center, the user runs in access mode, occupying concurrent authorization. 3. If "Allow unauthorized users to run in access mode" is not checked in "Advanced Settings": * (1) If the app integrating the SDK is not authorized to a user in the App Center, the user cannot access using this app. * (2) If the app integrating the SDK is authorized to a user in the App Center, the user can access using this app, occupying concurrent authorization and UEM mobile authorization. **Note:** Using SFSDKModeSupportMutable mode dynamically switches SFSDKModeSupportVpn and SFSDKModeSupportVpnSandbox based on your current server console configuration. Switch description: *If checked, it means the current SDK application allows unauthorized users to log in in access mode: The current switch function is only supported on server version 2.2.10 and above.* ### SFSDKFlags Options: - **SFSDKFlagsVpnModeTcp**: TCP mode, currently required. - **SFSDKFlagsHostApplication**: Main application mode, choose one between main and sub-application mode. - **SFSDKFlagsSubApplication**: Sub-application mode, choose one between main and sub-application mode. - **SFSDKFlagsSVpnServer**: Connect to VPN server. If a specific server is connected, select this item for higher efficiency; otherwise, ignore this item (Sub-application must specify the connected server). - **SFSDKFlagsSdpServer**: Connect to aTrust server. If a specific server is connected, select this item for higher efficiency; otherwise, ignore this item (Sub-application must specify the connected server). ### Extra Configuration (NSNumber) Options: - **@(SFSDKExtrasDNSCacheTTL)**: User-defined external network DNS resolution cache TTL, in seconds. ``` -------------------------------- ### Example Usage of commonHttpsRequest Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_api_common_https_request Demonstrates how to use the commonHttpsRequest method in a TypeScript application. It shows the setup of URL, type, and value parameters, followed by calling the SDK's commonHttpsRequest method. The example also includes the implementation of the onRequestResult callback to handle successful requests (navigating to a new page) and failed requests (displaying an error message). ```typescript let url = "https://10.240.101.11"; //服务器地址 let type = "45454125415@checkAppUpdate"; // 请求类型 let value = "{\"userId\":\"1\",\"appVersion\":\"10.0\",\"type\":\"android\"}"; // 请求参数 (构成json字符串) SFUemSDK.getInstance().getSFAuth().commonHttpsRequest(this.url, this.type, this.data, this); public onRequestResult(message: SFBaseMessage): void { console.log(TAG, 'commonhttpsrequest onRequestResult: ', json.stringify(message)); this.loadingDialog.close(); if (message.mErrCode == 0) { promptAction.showToast({ message: '请求成功', duration: 3000 }); router.pushUrl({ url: 'pages/TestPage' }).then(() => { hilog.info(0x0000, 'developTag', '%{public}s', 'Succeeded in jumping to the TestNetWorkView page.'); }).catch((err: BusinessError) => { hilog.error(0x0000, 'developTag', 'Failed to jump to the TestNetWorkView page: %{public}s', JSON.stringify(err) ?? ''); }) } else { promptAction.showToast({ message: '请求失败:' + json.stringify(message), duration: 3000 }); } } ``` -------------------------------- ### Get Configuration Options Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_api_get_options Retrieves advanced configuration options using the getOptions method. ```APIDOC ## getOptions ### Description Retrieves advanced configuration options. ### Method Not specified (likely a method within a class, not a direct HTTP endpoint). ### Endpoint Not applicable (this appears to be a Java method call). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java String value = SFUemSDK.getInstance().getSFConfig().getOptions(SFSDKOptions.OPTIONS_KEY_AUTH_LANGUAGE); ``` ### Response #### Success Response - **String** - Returns the value corresponding to the key, may return null. #### Response Example ```json { "example": "// Example response depends on the specific key used" } ``` ### Enumeration SFSDKOptions **OPTIONS_KEY_AUTH_TIMEOUT**: Sets the authentication connection timeout. **OPTIONS_KEY_AUTH_LANGUAGE**: Sets the language environment, defaults to "zh_CN". ``` -------------------------------- ### Username and Password Authentication Scenario (Objective-C) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_demo_introduce Example code for the username and password authentication scenario within the MainApp. The specific implementation details are found in the `BasicSceneViewController` class. ```objective-c @implementation BasicSceneViewController //参考MainApp中 BasicSceneViewController实现 @end ``` -------------------------------- ### Username, Password, and SPA Enablement Scenario (Objective-C) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_demo_introduce Example code for the username, password, and SPA (Single Page Application) enablement scenario within the MainApp. The relevant code resides in the `SpaAuthViewController` class. ```objective-c @implementation SpaAuthViewController //参考MainApp中 SpaAuthViewController实现 @end ``` -------------------------------- ### Username, Password, and SMS Authentication Scene (Swift) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_demo_introduce Illustrates the structure for the second authentication page, which combines username/password with SMS verification. This serves as a guide for developers to implement this specific authentication flow using the SDK. ```swift struct SecondAuthPage { //参考SDKDemo中 SecondAuthPage } ``` -------------------------------- ### Username, Password, and SMS Authentication Scenario (Objective-C) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_demo_introduce Example code for the username, password, and SMS authentication scenario within the MainApp. The implementation is located in the `SecondAuthViewController` class. ```objective-c @implementation SecondAuthViewController //参考MainApp中 SecondAuthViewController实现 @end ``` -------------------------------- ### Initiate Sub-app Launch - Objective-C Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_main_app_integrate Provides an interface for the main app to actively launch a sub-app. It allows passing a bundle ID, reason, and custom data for the launch. ```objective-c [[SFUemSDK sharedInstance].launch launchApp:@"com.test.bundleID" reason:SFLaunchReasonSubappAuthBack extraData:@"用户自定义数据" completeHandler:^(BOOL success) { // 回调结果 }]; ``` -------------------------------- ### Example of Resetting Password using SFUemSDK (TypeScript) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_api_resetPassword Demonstrates how to use the resetPassword method from SFUemSDK. It shows how to instantiate the SDK, access the authentication module, and provide an anonymous object for the SFResetPasswordListener with toast notifications for success and failure. ```TypeScript SFUemSDK.getInstance().getSFAuth().resetPassword(this.oldPassword, this.newPassword, { onPasswordChangedSuccess() { promptAction.showToast({ message: '修改密码成功' }) }, onPasswordChangedFailed() { promptAction.showToast({ message: '修改密码失败' }) } }) ``` -------------------------------- ### Handle Post-Authentication Sub-app Launch - Objective-C Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_main_app_integrate Implements logic to launch a sub-app after successful authentication. If a launch was pending due to the user not being logged in, this ensures the sub-app is launched with the saved information. ```objective-c /** 认证成功 */ - (void)onAuthSuccess:(BaseMessage *)msg { NSLog(@"AuthViewController onLoginSuccess"); if (self.launchInfo) { [[SFUemSDK sharedInstance].launch launchApp:@"com.test.bundleID" reason:SFLaunchReasonSubappAuthBack extraData:@"用户自定义数据" completeHandler:^(BOOL success) { // 回调结果 }] self.launchInfo = nil; } } ``` -------------------------------- ### Start Password Authentication (Objective-C) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_api_user_password_auth Initiates primary authentication using a username and password. This method is intended for initial authentication only and requires a non-null delegate to be set beforehand. The username provided does not need to include the authentication domain. ```objectivec - (void)startPasswordAuth:(NSURL * __nonnull)url userName:(NSString * __nonnull)username password:(NSString * __nonnull)password; // 用户名密码认证 NSURL *vpnUrl = [NSURL URLWithString:@"https://10.242.1.24"]; NSString *username = @"sangfor"; NSString *password = @"123"; [[SFUemSDK sharedInstance] startPasswordAuth:vpnUrl userName:username password:password]; ``` -------------------------------- ### Initialize SDK in Application Class (Java) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_demo_introduce Demonstrates the SDK initialization process within the Application class, specifically in the `attachBaseContext` method. This is the recommended place for initialization to ensure SDK capabilities are available in multi-process scenarios. It also shows the initialization of a Global Listener Manager. ```java public class SFApplication extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); sContext = base; /** * 初始化sdk,推荐在attachBaseContext中调用,因为sdk延后初始化会导致多进程场景下,子进程无法拥有sdk的能力 */ initSdk(base); GlobalListenerManager.getInstance().init(base); } } ``` -------------------------------- ### Register Logout Listener Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_primary_sms_auth Registers a listener to monitor logout events. Logout can be initiated by the application or the server administrator. It's recommended to register this listener globally, for example, in the AppDelegate, to ensure no logout events are missed. ```Objective-C /** * 注册注销事件监听回调,推荐在AppDelegate里面监听,可以做到全局监听,方便统一处理注销事件 */ [[SFUemSDK sharedInstance] registerLogoutDelegate:self]; ``` -------------------------------- ### Initialize SDK - Objective-C Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_api_initialize Initializes the SDK with specified modes, flags, and optional extra configurations. This method must be called before any other SDK interface and should only be invoked within didFinishLaunchingWithOptions on the main thread. It supports different SDK modes and flags for VPN, security sandbox, and application types, along with extra configurations like DNS cache TTL. ```Objective-C // 初始化 [[SFUemSDK sharedInstance] initSDK:SFSDKModeSupporVpnSandbox flags:SFSDKFlagsHostApplication | SFSDKFlagsVpnModeTcp extra:nil]; ``` -------------------------------- ### Start SMS Primary Authentication Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_primary_sms_auth Initiates the primary SMS authentication process. The SDK will return the authentication result through the onAuthSuccess, onAuthFailed, or onAuthProgress callbacks. Requires the server URL and the phone number formatted as '86-xxxxxxxxxxx@sms'. ```Objective-C NSURL *url = [NSURL URLWithString:@"https://10.242.1.24"]; NSString *phoneNumber = @"86-185xxxxxx8626@sms"; /** * 开始短信主认证,认证结果会在认证回调onAuthSuccess,onAuthFailed,onAuthProgress中返回 * @param url 请求认证的服务器地址信息 * @param phoneNumber 手机号码:86-xxxxxxxxxxx@认证域 */ [[SFUemSDK sharedInstance].auth startPrimarySmsAuth:url phoneNumber:phoneNumber]; ``` -------------------------------- ### Configure Gradle for SDK Demo Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_demo_introduce This snippet shows the necessary Gradle configurations for the SDK Demo, including the Gradle wrapper version and the Android Gradle plugin version. Ensure these versions are compatible with your local Android Studio setup to avoid compilation issues. ```gradle #gradle-wrapper.properties distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip #build.gradle dependencies { classpath 'com.android.tools.build:gradle:4.1.1' } ``` -------------------------------- ### Launch Main Application for Authentication Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_sub_app_integrate Launches the main application to obtain authorization for the sub-application. It includes checks to determine if the main app is installed and constructs the appropriate URL for launching. This function is crucial for scenarios where silent login fails or after a logout event. ```objectivec /** * Demo 封装一个方法用来拉起主应用,方便使用 */ - (void)launchMainApp { /** * 注意事项: * 1. 主应用需要配置格式为SFEasyApp.bundleId的URLScheme,用于拉起主应用 * 2. 子应用如果需要判断主应用是否安装,配置主应用的URLScheme到LSApplicationQueriesSchemes白名单 */ NSString *mainAppBundleId = @"com.sangfor.sdktest"; NSURL *mainAppOpenURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@.%@://", SFEASYAPP_PREFIX, mainAppBundleId]]; // 判断主应用是否安装 if ([[UIApplication sharedApplication] canOpenURL:mainAppOpenURL]) { NSLog(@"main app installed"); } else { NSLog(@"main app uninstalled"); [AlertUtil showAlert:@"主应用未安装" message:nil completion:^{ // AlertUtil is a placeholder for an actual alert utility exit(0); }]; } [[[SFUemSDK sharedInstance] launch] launchApp:mainAppBundleId reason:SFLaunchReasonHostappAuthAuthorization extraData:nil completeHandler:^(BOOL success) { // 回调结果 }]]; } ``` -------------------------------- ### Configure Obfuscation Rules for Sangfor SDK Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_development_environment This snippet provides the necessary ProGuard or R8 rules to prevent the Sangfor SDK's classes from being obfuscated. If your project uses code obfuscation, adding these rules is crucial to avoid runtime errors when calling SDK interfaces. It specifically whitelists classes starting with 'com.sangfor.' and 'android.'. ```proguard -keep class com.sangfor.** {*;} -keep class android.** {*;} ``` -------------------------------- ### Initialize and Register SDK Event Listeners (Objective-C) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_demo_introduce Initializes the SDK and registers for logout event listeners. The initialization mode `SFSDKModeSupportVpnSandbox` is recommended for VPN and sandbox capabilities. The `flags:SFSDKFlagsHostApplication` indicates the current integration app is the main application. Event listeners are best handled in AppDelegate for global scope. ```objective-c @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { /** * SDK的初始化模式只能放在didFinishLaunchingWithOptions中 * 建议配置为SFSDKModeSupportVpnSandbox,表示同时启动VPN和沙箱能力。如果您确定不需要沙箱能力,那么请改成SFSDKModeSupportVpn * 配置为SFSDKFlagsHostApplication,表示当前集成应用是主应用。 */ SFSDKMode mode = SFSDKModeSupportVpnSandbox; [[SFUemSDK sharedInstance] initSDK:mode flags:SFSDKFlagsHostApplication extra:nil]; /** * 注销事件监听回调,推荐在AppDelegate里面监听,可以做到全局监听,方便统一处理注销事件 */ [[SFUemSDK sharedInstance] registerLogoutDelegate:self]; } @end ``` -------------------------------- ### Username and Password Authentication Scene (Swift) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_demo_introduce Provides a reference for implementing the username and password authentication scenario within the SDK Demo. This structure is intended to be a placeholder for the actual implementation details found in the Demo. ```swift struct BasicScenePage { //参考SDKDemo中 BasicScenePage } ``` -------------------------------- ### Start Primary SMS Authentication - JavaScript Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_api_primary_sms_auth Initiates the primary SMS authentication process using the provided server URL and phone number. This function is intended for first-time authentication only. Ensure a callback listener is set prior to invocation. ```javascript startPrimarySmsAuth(url: string, phoneNumber: string): void; ``` -------------------------------- ### Get Option Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/api/advanced/ios_sdk_api_get_option Retrieves the value for a specified SDK configuration option. ```APIDOC ## GET /config/option ### Description Retrieves the value for a specified SDK configuration option. ### Method GET ### Endpoint `/config/option` ### Parameters #### Query Parameters - **optionKey** (SFSDKOption) - Required - The SDK configuration option to retrieve. ### Request Example ```json { "optionKey": "SFSDKOptionAuthTimeOut" } ``` ### Response #### Success Response (200) - **value** (NSString *) - The string value corresponding to the requested `optionKey`. Can be nil. #### Response Example ```json { "value": "120" } ``` ### Error Handling - Returns nil if the optionKey is not found or has no set value. ``` -------------------------------- ### Master Application Launch Handling (Objective-C) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_demo_introduce Code example for the master application's handling of being launched by a subordinate application. This involves setting an app launch delegate in `AppDelegate` to receive callbacks via the `onAppLaunched` method when a subordinate app initiates the launch. ```objective-c @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { /** * 注册拉起回调接口,当被子应用拉起时,会回调onAppLaunched函数 */ [[[SFUemSDK sharedInstance] launch] setAppLaunchDelegate:self]; } - (void)onAppLaunched:(SFLaunchInfo *)launchInfo { //参考MainApp中 此函数实现 } @end ``` -------------------------------- ### GET /isSpaSeedExist Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_api_spa Proactively checks if a SPA seed exists for a given server address. ```APIDOC ## GET /isSpaSeedExist ### Description Proactively checks if a SPA seed exists for a given server address. ### Method GET ### Endpoint /isSpaSeedExist ### Parameters #### Path Parameters None #### Query Parameters - **url** (String) - Required - The server address to check. #### Request Body None ### Request Example ``` GET /isSpaSeedExist?url=https://10.242.4.236 ``` ### Response #### Success Response (200) - **isExist** (boolean) - Returns `true` if the SPA seed exists, otherwise returns `false`. #### Response Example ```json { "isExist": true } ``` ``` -------------------------------- ### SFLog Get SDK Log Directory API Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_api_log Retrieves the path to the SDK's log directory. ```APIDOC ## GET /SFLog/getSDKLogDir ### Description Retrieves the path to the SDK's log directory. ### Method GET ### Endpoint /SFLog/getSDKLogDir ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **logDirectory** (String) - The path to the SDK log directory. #### Response Example ```json { "logDirectory": "/var/log/sdk/" } ``` ``` -------------------------------- ### Get Password Strategy Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_api_getPswStrategy Retrieves the password modification rules and strategy from the SDK. ```APIDOC ## GET /getPswStrategy ### Description Retrieves the rules and strategy for modifying passwords. ### Method GET ### Endpoint `getPswStrategy` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java SFUemSDK.getInstance().getPswStrategy(new SFGetPswStrategyListener() { @Override public void onGetPswStrategy(String displayTitle, String pwdRuleJson) { // Handle the retrieved password strategy } }); ``` ### Response #### Success Response (200) - **displayTitle** (String) - A formatted string describing the password rules for display. - **pwdRuleJson** (String) - A JSON string containing detailed password rule configurations and enable/disable flags. #### Response Example ```json { "code": 0, "message": "成功", "data": { "changeFirstLogin": 1, "effectiveTime": 90, "enablePswExpire": 0, "enablePswLength": { "enable": 1, "value": 8 }, "enablePswCombination": { "enable": 1, "value": { "enableAllLetter": 0, "enableNumber": 1, "enableUpperAndLowerLetter": 0, "enableSpecialLetter": 0 } }, "enablePswNotContainName": 1, "enablePswNotEqualHistory": { "enable": 1, "value": 3 }, "notBelongToWeakDb": 1, "notContainContChar": { "enable": 1, "value": 3 }, "notContainKeyboardContChar": { "enable": 1, "value": 3 }, "oldEnableSpecialLetter": 0, "changeMangerResetPwd": 0 }, "displayStrategyTitle": { "enablePswLength": "密码长度至少8位", "enablePswCombinationEnableAllLette": "", "enablePswCombinationEnableNumber": "密码需要包含数字", "enablePswCombinationEnableUpperAndLowerLetter": "", "enablePswCombinationEnableSpecialLetter": "", "enablePswNotContainName": "密码不能包含用户名", "enablePswNotEqualHistory": "", "notBelongToWeakDb": "密码不能为弱密码", "notContainContChar": "密码不能包含3位连续重复字符", "notContainKeyboardContChar": "密码不能包含键盘连续字符或者常规连续字符", "oldEnableSpecialLetter": "" } } ``` ### Error Handling - **400 Bad Request**: If the request is invalid. - **500 Internal Server Error**: If there is a server-side issue. ``` -------------------------------- ### Launch Host App for Authorization Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_api_launch_host This API allows a sub-application to initiate a login authorization request with the main application. ```APIDOC ## POST /launchHostApp ### Description Calls this interface to launch the main application to apply for login authorization. ### Method POST ### Endpoint /launchHostApp ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **context** (context) - Required - The context object. - **packageName** (String) - Required - The package name of the main application. - **launchReason** (SFLaunchReason) - Required - The reason for launching the host app. Refer to Common Data Structures -> SFLaunchReason Enum Parsing for details. - **extralData** (Bundle) - Optional - Additional data to carry, used for expansion. ### Request Example ```json { "context": "", "packageName": "com.main.app", "launchReason": "LOGIN_AUTHORIZATION", "extralData": { "key": "value" } } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### POST /startPasswordAuth Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_api_user_password_auth Initiates primary authentication using username and password. This method should only be used for the first authentication attempt. ```APIDOC ## POST /startPasswordAuth ### Description Initiates primary authentication using username and password. This method should only be used for the first authentication attempt; subsequent or secondary authentications cannot use this interface. ### Method POST ### Endpoint /startPasswordAuth ### Parameters #### Request Body - **url** (string) - Required - The server address. Example: `https://10.244.3.23` - **username** (string) - Required - The username. Example: `sangfor` - **password** (string) - Required - The user's password. Example: `123` ### Request Example ```json { "url": "https://10.244.3.23", "username": "sangfor", "password": "123" } ``` ### Response #### Success Response (200) - **message** (string) - A success message indicating the authentication process has started. #### Response Example ```json { "message": "Password authentication initiated successfully." } ``` ### Notes 1. Before calling this interface, you must have called `setAuthResultListener` to set a non-null callback, otherwise an exception will be thrown. 2. In a master-slave scenario, the child application cannot call this method. ``` -------------------------------- ### Get Authentication Status Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_api_getauthstate Retrieves the current authentication status of the user. This is a synchronous interface. ```APIDOC ## Get Authentication Status ### Description Retrieves the current authentication status information. This is a synchronous interface. ### Method GET ### Endpoint /sdk/auth/status ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **authStatus** (SFAuthStatus) - The current authentication status. #### Response Example ```json { "authStatus": 3 } ``` ### SFAuthStatus Enum | Value | Description | |---|---| | 0 | AuthStatusNone (Not authenticated) | | 1 | AuthStatusLogining (VPN authentication in progress) | | 2 | AuthStatusPrimaryAuthOK (Primary authentication successful) | | 3 | AuthStatusAuthOk (VPN authentication successful) | | 4 | AuthStatusLogouting (Logging out in progress) | | 5 | AuthStatusLogouted (Logged out) | ### Example Code ```java // Get the current authentication status SFAuthStatus authStatus = SFUemSDK.getInstance().getAuthStatus(); if (authStatus == SFAuthStatus.AuthStatusAuthOk) { SFLogN.info(TAG, "Current authentication successful"); } ``` ``` -------------------------------- ### Initialize SDK with initSDK - JavaScript Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_api_initialize Initializes the SDK using the `initSDK` function. This function must be called before any other SDK interfaces. It requires context, SDK mode, SDK flags, and optional extra parameters. The initialization must be performed on the main thread. ```JavaScript onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { /** * SDK初始化 */ this.init(); } init() { let extra: Map = new Map(); let sdkFlags: number = 0; sdkFlags = SFSDKFlags.FLAGS_HOST_APPLICATION; //表明是单应用或者是主应用 sdkFlags |= SFSDKFlags.FLAGS_VPN_MODE_TCP; //表明使用VPN功能中的TCP模式 SFUemSDK.getInstance().initSDK( this.context, SFSDKMode.MODE_SUPPORT_MUTABLE, sdkFlags, extra ); } ``` -------------------------------- ### Get SFLog Directory Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_api_log Retrieves the absolute path to the directory where the SDK stores its log files. This function does not take any parameters and returns a string representing the path. ```Objective-C - (NSString *)getSDKLogDir; ``` ```Objective-C // 获取SDK日志路径 NSString *path = [SFUemSDK sharedInstance].loggetSDKLogDir; ``` -------------------------------- ### Initialize aTrust SDK in Android - Java Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_api_initialize This snippet demonstrates how to initialize the aTrust SDK within an Android application. It highlights the recommended practice of calling `initSDK` in `attachBaseContext` and configures various SDK flags such as host application mode, TCP mode, and file isolation with a specified log path whitelist. The initialization requires a Context, SFSDKMode, and SFSDKFlags, along with optional extra configurations. ```java @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // 推荐在Application的attachBaseContext初始化SDK initSDK(base); } private void initSDK(Context context) { int sdkFlags = 0; // 主应用(或者子应用,只能二选一) sdkFlags = SFSDKFlags.FLAGS_HOST_APPLICATION; // TCP模式(必选) sdkFlags |= SFSDKFlags.FLAGS_VPN_MODE_TCP; // 额外参数(如开启文件加密隔离后如何给用户程序日志路径加白) sdkFlags |= SFSDKFlags.FLAGS_ENABLE_FILE_ISOLATION; // 开启文件加密隔离 JSONObject fileRuleObject = new JSONObject(); JSONArray whiteList = new JSONArray(); whiteList.put("/storage/emulated/0/userLogDir"); whiteList.put("/sdcard/app/logDir"); fileRuleObject.put(EmmPolicyConstants.FILE_WHITELIST, whiteList); // "{\"whiteList\":[\"/storage/emulated/0/userLogDir\", \"/sdcard/app/logDir\"]}" // 需要加白的日志路径JSON格式 String logPath = fileRuleObject.toString(); Map extra = new HashMap<>(); extra.put(SFSDKExtras.EXTRA_KEY_FILE_ISOLATION, logPath); SFUemSDK.getInstance().initSDK(context,SFSDKMode.MODE_VPN_SANDBOX, sdkFlags, extra); } ``` -------------------------------- ### Get SDK Log Directory (TypeScript) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/harmony_sdk_api_log Retrieves the directory path where the SDK stores its logs. This method requires no parameters and returns a string representing the log directory. ```typescript let dir: string = SFUemSDK.getInstance().getSFLog().getSDKLogDir(); ``` -------------------------------- ### Example Usage of unregisterLogoutListener - TypeScript Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/callbackApi/harmony_sdk_api_logout_callback Illustrates the call to unregister a logout listener. This code snippet shows how to invoke the unregister method with a previously defined listener object. ```typescript SFUemSDK.getInstance().unregisterLogoutListener(logoutListener); ``` -------------------------------- ### Initialize SDK (Objective-C) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/ios/ios_sdk_username_password_auth Initializes the SDK with specified modes and flags. This must be called after the application launches and before other SDK interfaces are used. SFSDKModeSupportMutable is recommended for dynamic capability changes. ```objectivec - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. /** * SDK的初始化模式只能放在didFinishLaunchingWithOptions中 * 建议配置为SFSDKModeSupportMutable,表示当前应用的能力(零信任VPN的接入能力和数据防泄密能力)可以根据服务端配置动态变更 * 配置为SFSDKFlagsHostApplication,表示当前集成应用是主应用。 */ SFSDKMode mode = SFSDKModeSupportMutable; [[SFUemSDK sharedInstance] initSDK:mode flags:SFSDKFlagsHostApplication extra:nil]; ... } ``` -------------------------------- ### Initialize Sangfor SDK (Java) Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/android/android_sdk_username_password_auth Initializes the Sangfor SDK, which is required before calling any other SDK interfaces. It's recommended to place this in `attachBaseContext` to ensure proper functionality across different processes. This initialization configures core SDK features and can enable features like VPN access and data loss prevention. ```java protected void attachBaseContext(Context base) { super.attachBaseContext(base); initSDK(base); } /** * 初始化SangforSDK * @param context */ private void initSDK(Context context) { Map extra = new HashMap<>(); int sdkFlags = SFSDKFlags.FLAGS_HOST_APPLICATION; sdkFlags |= SFSDKFlags.FLAGS_VPN_MODE_TCP; SFUemSDK.getInstance().initSDK(context, SFSDKMode.MODE_SUPPORT_MUTABLE, sdkFlags, extra); } ``` -------------------------------- ### Example Usage of registerLogoutListener - TypeScript Source: https://bbs.sangfor.com.cn/atrustdeveloper/appsdk/harmony/callbackApi/harmony_sdk_api_logout_callback Demonstrates how to register the current object as a logout listener using SFUemSDK. This snippet shows the typical invocation pattern for the registration method. ```typescript // 注册注销回调 SFUemSDK.getInstance().registerLogoutListener(this); ```