Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
Dan_vL
Product and Topic Expert
Product and Topic Expert

           

AuthProxy

The WebView used in a Cordova application does not prompt the user for credentials or for a client certificate as a regular browser does when this information is not provided.  In addition, on iOS the WebView does not provide any feedback when incorrect credentials are used.

  The AuthProxy plugin can be used to handle the communication for an app and as of SP04 will present a dialog for the user to enter credentials or to choose a client certificate when the option SAPKapselHandleHttpRequests is set to true.

When an app needs to provide a certificate to the server to identify itself this is known as client authentication or mutual authentication.  An example of this is if you are required to provide a client certificate as part of the onboarding process to register with an application or perhaps to access an OData provider (not needed to complete the example).  This occurs mostly in Business to Business (B2B) applications.  This is different from most business to consumer or B2C websites where it is only the server that authenticates itself to the client with a certificate that has been signed by a certificate authority (CA) such as an online banking site. For additional details on the AuthProxy plugin see the JavaScript file in a project that includes this plugin at

project_name\www\plugins\com.sap.mp.cordova.plugins.authproxy\www\authproxy.js

or the JS Documentation at Kapsel AuthProxy API Reference.

The following two examples demonstrate the functionality of the AuthProxy plugin.
Making an OData request through the AuthProxy Plugin
Using Client Certificates

Making an OData request through the AuthProxy Plugin

The following steps will demonstrate what happens when an incorrect password is sent to a backend OData endpoint and how this behavior can be improved with the AuthProxy plugin.

  • Modify the sample from the Logon Plugin section.
    In the management cockpit, change the SSO mechanism to be basic rather than Technical User (Basic).
    The authentication provider should be changed to be use a System Login module with the user name and password used to access the OData backend. 

  • In index.html, change the user and password fields in the context object to contain the correct user name and password for the OData endpoint.
    Add the following button below the Unlock button.
    <button id="chgPwd" onclick="sap.Logon.changePassword(logonSuccessCallback, errorCallback)">Change Password</button>
  • As of SP05, the Logon plugin has a dependency on the AuthProxy plugin.
    Edit C:\Kapsel_Projects\LogonDemo\config.xml and add the following setting.  Note that in SP07, this value defaults to true for iOS and false for Android via the platform config.xml and setting the value here will overwrite it.
    <preference name="SAPKapselHandleHttpRequests" value="false" />
  • Run
    cordova prepare
    Run the example and choose Unregister, Register, provide the valid username and password, and then once registered, click on Read.  Notice that the data is returned. 

    On Android, click on the change password button and change it to an invalid value.  Exit the app and remove it from memory.  Reopen the app and press the read button.  On Android the 401 exception is returned.


    On iOS, no error message occurs and no data is returned.


  • The following steps demonstrate how this can be improved when the AuthProxy plugin intercepts the requests.

    If using SP04 or later, edit C:\Kapsel_Projects\LogonDemo\config.xml and instruct the AuthProxy plugin to handle HTTP requests.
    <preference name="SAPKapselHandleHttpRequests" value="true" />
  • Copy the contents of the www folder to the platform specific www folder of the project using prepare.
    cordova prepare
  • Use Xcode to deploy and run the project.  Notice that this time if using SP04 or greater the user is prompted to enter the correct credentials and the realm of the site requesting the credentials is shown.


  • If the OData connection is proxied through the SMP 3.0 server and the OData endpoint challenges for credentials, the AuthProxy plugin will first send the credentials used in the registration to the SMP 3.0 server.  If those fail, then the credential screen is shown.

Using Client Certificates

This example will demonstrate how to use the AuthProxy plugin to register with the SMP 3.0 server using a client certificate and how to use a client certificate in a request to access an OData endpoint.  Before continuing, complete HTTPS in the Security Appendix as this is required to be setup before adding client authentication.

The Open SSL Toolkit will be used to create a certificate authority that will sign a client certificate.



Note this example is not using the Logon plugin to perform the registration as the Logon plugin requires using SAP Afaria to provide a client certificate or as of SP03, the CertificateProvider interface.  See SAP Afaria and Kapsel and X.509 Certificate Interface for additional details on how to use client certificates with the Logon plugin.

This example can be run on an Android device or emulator or an iOS device or an iOS 7 simulator.  The server certificate must be installed onto the device's system store which is not possible in an iOS simulator prior to version 7.0.

Note, the following instructions are meant for demonstration purposes only.  Security in a production environment should be managed by your company's security professional.

  • Modify the serverkey for port 8082 which is configured for client authentication.  Change the keyAlias from smp_crt to serverkey.  Note, changes to this file require a server restart before they take effect.
    C:\SAP\MobilePlatform3\Server\config_master\org.eclipse.gemini.web.tomcat\default-server.xml

    <Connector smpConnectorName="mutualSSL" protocol="com.sap.mobile.platform.coyote.http11.SapHttp11Protocol"
        port="8082" maxThreads="200"
        scheme="https" secure="true" SSLEnabled="true"
        ciphers="TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
        keyAlias="serverkey" clientAuth="true" sslProtocol="TLS" sslEnabledProtocols="TLSv1.2,TLSv1.1,TLSv1"/>
       
  • If on windows, download the Open SSL Toolkit from Shining Light Productions.  Specifically download the latest Win64 OpenSSL v1.0.1 Light and if required Visual C++ 2008 Redistributables (x64).

  • Create a batch file to set the path and add an environment variable.  In a command window execute the bat file.
    PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Java\jdk1.7.0_45\bin;C:\OpenSSL-Win64\bin;

    set OPENSSL_CONF=c:\OpenSSL-Win64\bin\openssl.cfg
  • A useful tool for examining a server port is to run the following commands.
    openssl s_client -connect localhost:8080 > c:\temp\8080.txt
    openssl s_client -connect localhost:8082 > c:\temp\8082.txt
    8080.txt will contain the following text.
    no peer certificate available
    ---
    No client certificate CA names sent
    Which indicates that the server is not using a certificate (ie, no https, no encryption, or identification).

    8082.txt is interesting in that it will indicate what the acceptable list of certificate authorities that the server will accept is.  This means that it will only accept a client certificate that has been signed by one the listed certificate authorities.
    Acceptable client certificate CA names
    /C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 1999 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 4 Public Primary Certification Authority - G3
    /C=US/O=Equifax/OU=Equifax Secure Certificate Authority
    ...
    /C=CA/ST=Ontario/L=Waterloo/O=SAP/OU=SAP Canada/CN=demoRootCA
    The last entry will appear after following the steps below which are to create a certificate authority named demoRootCA which will be used to sign a client certificate named user1.  After following the below instructions, an app will be created that will be able to pass in a client certificate named user1 to the SMP 3.0 server during the registration process and the SMP 3.0 server will accept the registration because it will trust the certificate authority named demoRootCA.

  • Edit the file C:\OpenSSL-Win64\bin\openssl.cfg.  Under the heading CA_default a set of directories are specified and the names of various files such as the CA certificate, the private_key name of the CA certificate.  Set these two to a value such as demoRootCA.

  • Under the section req_distinguished_name, add properties where desired so that default values are provided.  The following are a few examples
    countryName                        = Country Name (2 letter code)
    countryName_default           = CA
    stateOrProvinceName          = State or Province Name (full name)
    stateOrProvinceName_default     = Ontario

    localityName                         = Locality Name (eg, city)
    localityName_default            = Waterloo

    0.organizationName              = Organization Name (eg, company)
    0.organizationName_default  = SAP

  • Create the directory structure and required files for Open SSL.
    cd C:\OpenSSL-Win64
    mkdir certs
    cd certs
    mkdir demoCA
    cd demoCA
    type NUL > index.txt
    echo 01 > serial
    mkdir newcerts
    mkdir private
    cd C:\OpenSSL-Win64\certs
  • Create a private key for the CA.
    openssl genpkey -des3 -out demoRootCA.key -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -pass pass:112233
  • Self-sign the CA and move the private key to the private folder.
    openssl req -new -x509 -days 3650 -key demoRootCA.key -out demoRootCA.crt
    move demoRootCA.crt demoCA
    move demoRootCA.key demoCA\private
  • Import CA into SMP 3.0 keystore and restart the server.
    keytool -import -deststorepass changeit -destkeystore C:\SAP\MobilePlatform3\Server\configuration\smp_keystore.jks -file demoCA\demoRootCA.crt -alias demoRootCA
    The SMP 3.0 server will now accept client certificates that have been signed by this certificate.

  • The demoRootCA can be viewed using the following command.
    keytool -list -v -keystore C:\SAP\MobilePlatform3\Server\configuration\smp_keystore.jks -alias demoRootCA -storepass changeit
  • Create a private key for a client cert.
    openssl genpkey -des3 -out user1.key -algorithm RSA -pass pass:changeit
  • Generate a signing request for the client cert.
    openssl req -new -key user1.key -out user1.csr -passin pass:changeit
    Note, enter can be pressed for the question A challenge password.

  • Use the CA to sign the client cert.
    openssl ca -out user1.crt -infiles user1.csr
  • Package up the private and public client key in a format that can be imported into a desktop browser or a mobile device.  The public and private key of the client certificate must be imported to the mobile device so the PKCS12 format is used.
    openssl pkcs12 -export -out user1.p12 -inkey user1.key -in user1.crt -name user1 -certfile demoCA\demoRootCA.crt -passin pass:changeit -passout pass:changeit
  • Follow the steps shown in Configuring a Kapsel App in the Management Cockpitto create an Application with the application id of
    com.mycompany.authproxy
    Set the endpoint to be
    https://sapes1.sapdevcenter.com/sap/opu/odata/IWFND/RMTSAMPLEFLIGHT
    The alias name should match the alias name of a certificate in the smp_keystore.jks that is used to access the OData source.


    Note that the operation will be processed in the context of the client's certificate (The SSL_CLIENT_CERT header is passed along in the request).

    Create a new security provider and add an x.509 User Certificate authentication provider.


  • Import the user1.p12 file into the personal certificate store.  In Chrome, choose Settings > Show Advanced Settings > HTTPS/SSL > Manage certificates > Import > Change the file extension filter to *.p12 and browse to user1.p12.  Once completed the client certificate should appear as shown below.



    Note, Chrome may need to be started with the option --disable-web-security to enable this example to be run from the file system.  Ensure that all instances of Chrome are shut down before restarting. At this point the following register4.html can be used to test out client authentication using desktop Chrome.  It requires that the datajs library is placed in the same folder as register4.html.





    There is a registry setting that instructs which client certificate should be automatically selected by Chrome.  If you do not see a dialog to select a certificate after pressing the register button, it may be that there is a registry setting such as the one shown below which indicates that all web sites that request a client certificate should use a certificate signed by SSO_CA.
    [HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\AutoSelectCertificateForUrls]
    "1"="{\"pattern\":\"*\",\"filter\":{\"ISSUER\":{\"CN\":\"SSO_CA\"}}}"
      See also List of Policies for Chrome.

    Also note that Chrome will remember which certificate was selected until it is restarted.

  • The next step is to perform a registration using a client certificate from within an app running on a mobile device or simulator.  Create a new project which will perform client authentication to the SMP 3.0 server.
    cordova -d create C:\Kapsel_Projects\AuthProxyDemo com.mycompany.authproxy AuthProxyDemo "{\"plugin_search_path\":\"C:/SAP/MobileSDK3/KapselSDK/plugins/\"}"
    cd C:\Kapsel_Projects\AuthProxyDemo
    cordova -d platform add android

    cordova -d create ~/Documents/Kapsel_Projects/AuthProxyDemo com.mycompany.authproxy AuthProxyDemo "{\"plugin_search_path\":\"/Users/i826567/SAP/MobileSDK3/KapselSDK/plugins/\"}"
    cd ~/Documents/Kapsel_Projects/AuthProxyDemo
    cordova -d platform add ios
  • Add the Cordova console plugin and AuthProxy plugin.
    cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git cordova -d plugin add com.sap.mp.cordova.plugins.authproxy 
  • Replace www\index.html with the contents of index.html.
    Place a copy of datajs-1.1.2.min.js into the www folder.

  • Copy the files to the platform directory by running
    cordova -d prepare
  • The client certificate in this example for Android is placed in a location the application can access it from.  It could also be added to the device's trust store but on Android this results in the user having to accept that the application is using a certificate from the trust store.

    For Android
    adb push user1.p12 /mnt/sdcard/
    adb shell
    cd /mnt/sdcard
    ls
    exit
    For iOS
    The user1.p12 certificate must be added as part of the application by right-clicking on the Resource folder, select the menu item Add Files to "AuthProxyDemo"...
    Select the user1.p12 file.
    Click the Add button to add user1.p12 into the Xcode project.

    The client certificate can either be accessed directly from the file system via
    clientCert = new sap.AuthProxy.CertificateFromFile("/mnt/sdcard/user1.p12", "changeit", "user1");  //Android
    clientCert = new sap.AuthProxy.CertificateFromFile("user1.p12", "changeit", "user1");  //iOS
    On iOS, the certificate could be loaded from the certificate store after it is first loaded into the application's keychain via a call to CertificateFromFile before using CertificateFromStore.  In this example only CertificateFromFile is used.

    In addition to accessing the certificate from the file system and the device's secure store, the certificate can be accessed from the Logon plugin, assuming it was provisioned to it with Afaria or the X 509 Certficate Provider with the following call
    sap.AuthProxy.CertificateFromLogonManager("clientKey")
  • Use the Android IDE or Xcode to deploy and run the project.



    In order to successfully make OData requests using client authentication, the backend OData server would need to be configured which is not covered in this guide.

  • Note, on Android if the error Certificate file does not exist occurs and the file does exist at the location specified, make sure the  READ_EXTERNAL_STORAGE permission is in the AndroidManifest.xml file as shown below.
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    Alternatively if using Android 4.3 or lower modify Settings -> Developer Options -> Protect SD Card -> Uncheck

  • A new feature in SP04 for the AuthProxy plugin is the ability for the plugin to  display a credential selection screen if challenged for a client certificate.  In order to enable this feature change enable the AuthProxy plugin to intercept all requests by editing C:\Kapsel_Projects\LogonDemo\config.xml and add the following setting.
    <preference name="SAPKapselHandleHttpRequests" value="true" />
    Modify index.html and comment out the following two lines in the init and register methods.
    //OData.defaultHttpClient = sap.AuthProxy.generateODataHttpClient();  //In SP04, this method is no longer needed when using SAPKapselHandleHttpRequests
    ...
    //certificateSource : clientCert,
    Now when the SMP 3.0 server requests a client certificate, a dialog showing the available client certificates is shown.  Note the client certificates must be installed into the device's certificate store in order to be shown in the dialog.


    Note, that on Android, when using HTTPS and SAPKapselHandleHttpRequests, the AuthProxy plugin can only intercept HTTP requests and it will then send them as HTTPS.  Because of this, the following call must be made at the start of the register method.
    sap.AuthProxy.addHTTPSConversionHost(successCallback, errorCallback, "http://ykfn00528072a.amer.global.corp.sap"); 
    Add the following two methods
    function successCallback() {
        console.log("Success");
    }

    function errorCallback() {
        console.log("Error");
    }
    Also note that getSMPURL method needs to be changed from returning https to http.

    See also the method sap.AuthProxy.addHTTPSConversionHost in AuthProxy Plugin Overview.

  • Note that on iOS, only certificates that have been loaded into the applications keychain are available to be selected.  See Making Certificates and Keys Available To Your App and Finding a certificate for further details.  One way to simulate having multiple certificates installed into the applications keychain would be to comment out the call to sap.AuthProxy.deleteCertificateFromStore call and run the app twice registering each time with a different certificate such as user1.p12 and user2.p12.  In order to register twice, the unregister button would need to be pressed the second time the app was run.  At this point two certificates would be available in the applications keychain.  Now comment out the line of code in the init method that integrates with datajs and certificateSource : clientCert line in the register method and rerun the app again choosing unregister and register and notice this time that the user is prompted to request which certificate to use for the authentication challenge.


  • On Android the application has access to the Trusted Certificates store.  Because of this, it is possible to have the registration to the SMP server use the Logon plugin with mutual authentication without having to use Afaria or the X.509 Certificate provider interface.

    To modify the example from the Logon plugin section, in index.html, change the serverHost to be the fully qualified host name, the appId to be "com.mycompany.authproxy", the https context variable to be http, instead of https, the server port to be 8082 and add the following lines to the init method before the call to sap.Logon.init().
    sap.AuthProxy.startIntercepting(successCallback, errorCallback); //New in SP08, not needed in SP07. 
    sap.AuthProxy.addHTTPSConversionHost(successCallback, errorCallback, "
    http://YKFN00528072A.amer.global.corp.sap");
    Add the following two methods
    function successCallback() {
        console.log("Success");
    }

    function errorCallback() {
        console.log("Error");
    }
    Also ensure the below setting is set to true.
    <preference name="SAPKapselHandleHttpRequests" value="true" />
    When the Logon plugin attempts to register the AuthProxy plugin will intercept the request and since the server requires a client certificate to complete the request, it will show the Choose certficate dialog as shown below.


The below links contain some additional information on SSL, certificates, configuring a Tomcat server to use client authentication and how to add an OData producer to Tomcat.
Mutual Authentication
Tomcat SSL How To
Tomcat Mutual Authentication
OData4J
Hosting OData4J in Tomcat


Back to Getting Started With Kapsel

16 Comments