Table of Contents Title Page...... 1 Disclaimer...... 4 Release Information...... 5 Version History...... 5 Notes...... 5 Contact Information...... 5 Typographic Styles and Conventions...... 6 Introduction...... 7 Purpose...... 7 What Are Enterprise MicroApps?...... 7 System Concept Overview...... 8 System Components...... 8 Supported Functionality...... 8 End-User Environment...... 8 Enterprise MicroApp Management Environment...... 9 Development Environment...... 9 Development and Deployment Process...... 9 Creating a Data Service...... 10 Creating an Enterprise MicroApp...... 11 Configuring and Validating an Enterprise MicroApp...... 11 Consuming an Enterprise MicroApp...... 11 Configuring a System Environment...... 12 System Environment Configuration Scenario Overview...... 12 On-Premises Scenario...... 12 Hybrid Scenario...... 13 System Environment Configuration Details...... 14 Enterprise MicroApp Container...... 14 Firewall Traversal...... 15 Security and User Management...... 15 Developing an Enterprise MicroApp...... 17 Back-end Development...... 17 What is Data Service?...... 17 Creating and Configuring Data Service...... 17 Front-end Development...... 18 Browser iFrame-Base Enterprise MicroApp Development...... 18 Browser OpenSocial Enterprise MicroApp Development...... 18 Mobile Enterprise MicroApp Development...... 18 Desktop Enterprise MicroApp Development...... 19 Appendix - Firewall Traversal...... 20 Reverse Proxy...... 20 SAP Web Dispatcher...... 20 Third Party Reverse Proxy...... 20 Other Solutions...... 21 Google Secure Data Connector...... 21 Appendix - iFrame-base Enterprise MicroApp Development...... 22 iFrame-Based Enterprise MicroApps...... 22 What is Container Module?...... 22 What is Server Module?...... 22 Creating and Configuring iFrame-base Server Module...... 22 Creating and Configuring iFrame-base Container Module...... 32 Appendix - OpenSocial Enterprise MicroApp Development...... 36 OpenSocial Enterprise MicroApps...... 36 Google OpenSocial Gadget...... 36 Creating and Configuring OpenSocial Gadget...... 36 Appendix - Desktop Enterprise MicroApp Development...... 46 Creating Desktop Enterprise MicroApps...... 46 Recommended Application Structure...... 46 Desktop MicroApp Implementation details...... 47 Appendix - iPhone Enterprise MicroApp Development...... 55 Introduction...... 55 Using iPhone Application for Consuming SAP Data...... 55 General Information on Implementing Web Service Calls...... 56 Implementing a SOAP Web Service Call...... 56 Implementing a REST/JSON Web Service Call...... 62 Available Authentication Mechanisms...... 66 Supporting Basic Authentication...... 66 Supporting a Client Certificate Authentication...... 67 Supporting SAP Logon Ticket...... 68 Existing Development Documentation and Tools...... 69 Apple Standards and Guidelines...... 69 Memory Management Recommendations...... 69 Development Tools...... 69 Tips and Tricks...... 75 Controlling an Application Mode...... 75 Appendix - Single Sign-On Using Federated User Management...... 77 Single-Sign-On Using Federated User Management...... 77 Overview...... 77 SAP NetWeaver SAML Support...... 77 Using SAML with Enterprise MicroApps...... 77 Appendix - Single Sign-On Using Signed Fetch...... 81 SSO Using Signed Fetch...... 81 Overview...... 81 Using OAuth Signed Fetch with Enterprise MicroApps...... 81 Appendix - Single Sign-On Workaround...... 85 Single Sign-On Workaround...... 85 x.509 Client Certificate Authentication...... 85 Master Logon Enterprise MicroApp Authentication...... 87 MicroApps Technical User Guide - Disclaimer Disclaimer

© 2009 by SAP AG.

All rights reserved. SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.

Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the United States and in other countries. Business Objects is an SAP company.

All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary.

These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.

Page 4 of 88 MicroApps Technical User Guide - Release Information Release Information

Version History

Document Version Description Release Date 1.0 First official release of this guide September 2009 1.1 Added Appendix - Enterprise MicroApps iPhone October 2009 Development 1.1.1 Samples source code location is changed to http:// October 2009 wiki.sdn.sap.com/wiki/display/Img/Code+Samples 1.2 Updated chapter Configuring a Run-Time December 2009 Environment * Updated On Premises Scenario and Hybrid Scenario sections diagrams Updated Appendix - Configuring a Data Service * Added Configuring an SAP Enterprise Service as a Data Service - ABAP section * Added Testing a Data Service section Updated Appendix - Creating an Enterprise MicroApp Server Module * Added Deploying Enterprise MicroApps on the ABAP System Using BSP Applications section * Removed full code listings Updated Appendix - Configuring an Enterprise MicroApp Server Module * Added Configuring a BSP Application as an Enterprise MicroApp Server Module - ABAP 1.3 Restructure the document; the step-by-step February 2010 instructions were separated from the document and placed on the sample page at SDN Wiki, then the document structure was reorganized.

Notes

The sample implementations in this guide are verified using the NetWeaver 7.0 SP14. The sample implementations in this guide are verified using the NetWeaver 7.1 SP05.

Contact Information

For more information about Enterprise MicroApplication, please visit SAP Imagineering SDN wiki space located at: https://wiki.sdn.sap.com/wiki/display/Img/MicroApplications

Page 5 of 88 MicroApps Technical User Guide - Typographic Styles and Conventions Typographic Styles and Conventions

The following styles and conventions are used in this guide:

Typographic styles and conventions Convention Description Bold • Represents user interface items such as check boxes, command buttons, dialog boxes, drop-down list values, field names, menu commands, menus, option buttons, perspectives, tabs, tooltip labels, tree elements, views, and windows. • Represents keys, such as F9 or CTRL+A. • Represents a term the first time it is defined. Courier Represents file and directory names, code, system messages, and command-line commands. Courier Bold Represents emphasized text in code. Select File > Save As Represents a command to perform, such as opening the File menu and selecting Save As. Italic • Represents any information to be entered in a field. • Represents documentation titles. < > Represents placeholder values to be substituted with user specific values. Hyperlink Represents a hyperlink. Clicking a hyperlink displays the information topic or external source.

Page 6 of 88 MicroApps Technical User Guide - Introduction Introduction

Contents

• Purpose • What Are Enterprise MicroApps?

Purpose

This document serves as a user's guide for IT professionals and developers, and provides guidelines on:

• Setting up the Enterprise MicroApp system environment • Developing and deploying Enterprise MicroApps

What Are Enterprise MicroApps?

Enterprise MicroApps are small applications designed to extend a defined set of enterprise application functionality and transactions that is specific to a users role and requirements. Developers of Enterprise MicroApps leverage SAP NetWeaver enterprise and web services to securely deliver enterprise system functionality on desktops, within browsers, or mobile devices, and within cloud environments using gadgets, widgets, mobile applications, and other.

In order to consume Enterprise MicroApps, business users simply pick and select Enterprise MicroApps from the Enterprise MicroApp gallery space and add them on any container supported by the IT department. For example, a portal in the browser, a widget engine on the desktop, or a application container on the mobile device. Enterprise MicroApp gallery spaces are managed by the IT administrator; therefore the permission and usage of Enterprise MicroApps is completely under the control of IT department.

Enterprise MicroApps can be built using any language of choice by any developer, consuming either newly developed backend data services or already existing services, for example, enterprise services registered in SAP Enterprise Service Repository (SAP ESR).

Page 7 of 88 MicroApps Technical User Guide - System Concept Overview System Concept Overview

Contents

• System Components • Supported Functionality • Development and Deployment Process

System Components

The following diagram describes components and functionality of each building block:

Generic components diagram

Supported Functionality

The following sections describe the potential functionality that can be supported:

• End-User Environment • Enterprise MicroApp Management Environment • Development Environment

End-User Environment

The End-User Environment consists of Enterprise MicroApp Containers and Gallery, where end users can browse, select and consume business contents. The typical features include:

Page 8 of 88 MicroApps Technical User Guide - System Concept Overview

• Single Sign-On (SSO) among the Enterprise MicroApp containers, Enterprise MicroApp administration servers, and backend systems • Gallery space per user role, such as sales rep, line manager, employee, and other • Content discovery and recommendations • Feedback system to request a new Enterprise MicroApp or enhancement of an existing Enterprise MicroApp

Enterprise MicroApp Gallery may support Enterprise MicroApp Directory, where IT administrators can configure Enterprise MicroApp gallery spaces. The typical features include:

• Define user roles and group Enterprise MicroApps per user role • Default setting for personalization parameters • Validation of a newly developed or imported Enterprise MicroApp (test environment) • Import user role and Enterprise MicroApp role assignment data

Enterprise MicroApp Management Environment

The Management Environment offers the following functionalities:

Enterprise MicroApp Administration, where IT administrators can manage Enterprise MicroApp content and its usage. The typical features include:

• Publish or revoke an Enterprise MicroApp; role-Enterprise MicroApp assignment • User management, permission control, user-role assignment • Service APIs for exporting the role-Enterprise MicroApp assignment • Validation of a newly developed or imported Enterprise MicroApp (test environment) • Troubleshooting tool for isolating support issues

Data Service Management, where IT administrators can manage back-end data services. The typical features include:

• Back-end user mapping • Data service usage monitoring or metering • Data service import from a service registry • Back-end service connection

Development Environment

The Development Environment offers tools for developers to build and deploy Enterprise MicroApp components:

Tools for developing and deploying front-end modules(container-module, server-module): Front-end modules are usually specific to Enterprise MicroApp containers, therefore the development tools are provided by the vendor who runs the container. The typical features includes:

• Publish an Enterprise MicroApp entry into the gallery (test environment) • Build and deploy an Enterprise MicroApp container module run-time object, such as Google Gadget Module *.xml file • Build and deploy an Enterprise MicroApp application with UI design templates or a library • Consume a data service with the data service connector

Tools for developing and deploying Data Services: Enterprise MicroApp Data Services are based on SAP systems, and usually built and deployed using SAP development tools, such as NetWeaver Developer Studio or ABAP Workbench. The typical features includes:

• Mash up SAP back-end data and services, such as RFCs, BAPIs, etc. • Generate web services as Data Services out of SAP back-end RFCs • Deploy and publish a data service to a service repository (SAP Enterprise Service Repository, etc.)

Development and Deployment Process

The following diagram illustrates a typical development and deployment process flow.

Page 9 of 88 MicroApps Technical User Guide - System Concept Overview

Note: In this section, SAP NetWeaver (SAP NW) is used as a primary component to provide the back-end data service and its administration.

Development and deployment process flow The process consists of the following steps:

• Creating a Data Service • Creating an Enterprise MicroApp • Configuring and Validating an Enterprise MicroApp • Consuming an Enterprise MicroApp

Creating a Data Service

As an optional step, if there is no existing data service, developer (backend) can create a new data service.

1. Create a data service mashing up the backend data processing functions or services, such as SAP RFC, BAPI, enterprise service or any web service. 2. Alternatively, if there is existing SAP RFC function module, developer can generate a web service out of it, and use it as data service. 3. Deploy the data service onto a hosting server.

Page 10 of 88 MicroApps Technical User Guide - System Concept Overview Creating an Enterprise MicroApp

UI developer (frontend) can create an Enterprise MicroApp front-end module consuming the data service. The front-end module may consist of a container module, which is deployed and administrated on the container provided by third party vendor typically in cloud, and a server module, which is deployed and administrated on a server located on- premise of the enterprise behind the firewall.

1. Create an Enterprise MicroApp front-end module, i.e. container module and optionally server module, defining UI views and process flow control. 2. Deploy the Enterprise MicroApp server module, if applicable, to a server according to deployment scenarios. 3. Deploy the Enterprise MicroApp container module to the Enterprise MicroApp gallery space.

Note: Depending on the run-time environment configuration scenario and the Enterprise MicroApp programming model, the Enterprise MicroApp server module development step can be skipped.

Configuring and Validating an Enterprise MicroApp

IT administrator can configure, review and validate the submitted Enterprise MicroApp and data services, and then publish it to the production gallery.

1. Configure the data service that is required for the Enterprise MicroApp. 2. Configure the Enterprise MicroApp on the test run-time environment as required. 3. Test the Enterprise MicroApp. 4. Publish the Enterprise MicroApp to a production Enterprise MicroApp gallery space.

Consuming an Enterprise MicroApp

End user can consume an Enterprise MicroApp from the Enterprise MicroApp gallery space.

1. Browse the required Enterprise MicroApp gallery space. 2. Select and consume the selected Enterprise MicroApp.

Page 11 of 88 MicroApps Technical User Guide - Configuring a System Environment Configuring a System Environment

Contents

• System Environment Configuration Scenario Overview • System Environment Configuration Details

A system environment includes the following:

• End user environment: Enterprise MicroApp containers and gallery spaces for end users • Enterprise MicroApp management environment: Enterprise MicroApp administration and data service management for IT professionals

System Environment Configuration Scenario Overview

This section provides an overview of the following system environment configuration scenarios:

• On-Premises Scenario • Hybrid Scenario

On-Premises Scenario

In this scenario, IT professionals of the enterprise configure and manage individual MicroApps on premise of the enterprise. The server module, which provides the definition of MicroApps, is deployed on a server located on premise of the enterprise, and configured and managed by the IT professionals. The container module is deployed to a container in the cloud as a run-time object, for some cases as a wrapper of the server module, and used by end users. Primary user management and data service access control is also performed by the IT professionals on the server on premises. This configuration scenario is typically chosen when there is no or limited administration control given to IT professions for managing the Enterprise MicroApps in the containers (e.g. iGoogle, Netvibes, , or Yahoo Widget Engine).

Page 12 of 88 MicroApps Technical User Guide - Configuring a System Environment

On Premises scenario overview

Note: Enterprise MicroApp Gallery may be located on premise behind the firewall.

Hybrid Scenario

In this scenario, IT professionals of the enterprise configure and manage individual MicroApps on the third party environment in cloud. The container modules, optionally with the server modules, are deployed on a server hosted by the third party vendor who provides the container in the cloud. The Enterprise MicroApp, using the underlying API functions or services provided by the third party's container, accesses back-end data by calling data services that are hosted on a server on premises. Administration of the data services, for example the access control of each data service, is performed by the IT professionals on the server on premises. The user data may be managed separately between the third party's container and the back-end enterprise system. In that case, the user data between the two is usually synchronized or mapped. This configuration scenario is typically chosen when the enterprise uses one dedicated end-user environment, where there is a complete administration control given to IT professions for managing the Enterprise MicroApps in the containers (e.g. GoogleApps).

Page 13 of 88 MicroApps Technical User Guide - Configuring a System Environment

Hybrid scenario overview

System Environment Configuration Details

The following questions can help to determine how a system environment is configured and provide several guidelines for selecting configuration scenarios and various options:

1. Enterprise MicroApp Container: Which Enterprise MicroApp containers are supported? Examples of containers: • SAP Portal • OpenSocial container, such as Google Apps • Web browser iFrame-based container, such as Netvibes • Desktop containers, such as Yahoo Widget Engine • Mobile device, such as iPhone, BlackBerry 2. Firewall Traversal: Are end users allowed to access Enterprise MicroApps from the outside of the firewall? Examples of firewall traversal tools: • SAP Web Dispatcher • Third-party reverse proxy • Third-party specific tools 3. User Management: How and where user data and Enterprise MicroApp access control are managed? Is it centrally managed by one user management tool? Or is it managed separately per run-time environment? Is the Single-Sign- On (SSO) required between the run-time environment? Examples of SSO options: • User federation • User mapping • 3-legged user authentication

Enterprise MicroApp Container

The first question helps to determine the main deployment scenarios:

• On Premises scenario • Hybrid scenario

Page 14 of 88 MicroApps Technical User Guide - Configuring a System Environment

If Enterprise MicroApps are used not only in one particular container, but also in other containers, the On Premises scenario is more suitable as it provides a central management environment for Enterprise MicroApps. In the On Premises scenario, Enterprise MicroApps server modules are deployed and managed centrally by IT professionals on premise. The container modules are developed and deployed for each of the containers for supporting the end-user. In the Hybrid scenario, Enterprise MicroApps are hosted in third-party run-time and access data services via APIs that are provided by the third-party, e.g. OpenSocial API. Therefore, not only the Container Modules, but also the Server Modules are developed according to the third-party's run-time specifics, then deployed and managed per each of the third-party servers and containers. This scenario often requires more effort in developing and maintaining modules when multiple containers are supported.

Firewall Traversal

The second question clarifies firewall traversal requirements. If Enterprise MicroApps must be accessible to end users from outside of the company's firewall, a firewall traversal must be supported. The firewall traversal options are as follows:

• using reverse proxy, such as SAP Web Dispatcher • using third-party specific tool, such as Google Secure Data Connector

In the Hybrid System Configuration Scenario, it is mandatory to support the firewall traversal, either using a reverse proxy or using a third-party specific tool. In the Hybrid scenario, Enterprise MicroApp front-end modules, i.e. Container Modules and Server Modules and/or any underlying API functions, are hosted on a server in the cloud, which make a call to the back-end data services that are hosted on a server on premises. This requires a server-to-sever communication over the firewall. For more details on the firewall traversal options, please refer to Appendix: Firewall Traversal Examples.

Security and User Management

In order to provide secure access to back-end enterprise systems, Enterprise MicroApps content must be protected by an access-control mechanism supported by the run-time environment. To ensure minimum access control, Enterprise MicroApps content must be configured and accessible by users who are authenticated by the run-time environment. Depending on security and user management features supported by the run-time environment, it is possible to have more flexible access control, such as role-based access control. With this type of access control, an Enterprise MicroApp can be accessed only by users with a particular role. Note: Accessing Enterprise MicroApps' back-end data source can be configured separately using data service authorization. Therefore, even though a user can launch an Enterprise MicroApp, the Enterprise MicroApp can throw an error informing that the user does not have sufficient authorization for back-end data access.

In general, an Enterprise MicroApp run-time environment includes multiple servers, e.g. a server hosting MicroApp container, a server hosting Server Modules, or a server hosting back-end data services, these servers require user authentication individually. The third question helps to determine how to configure user authentication and single sign-on between multiple servers in a run-time environment.

Single Sign-On Options

MicroApps are accessed by the end-user on the MicroApp container as described in the previous section. The end- user is required to log in to the server where the MicroApp container is hosted, using his or her user id that is valid for the container. When the MicroApp makes a data access request to the server that hosts the back-end data services, it typically requires the end-user to log in using a separate user credential to access the back-end data service. In order to avoid this multiple user login issue, there are several options for enabling single-sign-on (SSO) between the servers.

SSO Using Federated User Management

When the end-user logs in the server hosting MicroApp container, the server can redirect the user authentication process to a central identity provider. The identity provider, upon a successful authentication of the user, can issue a token as the user's credential. This token is used when the MicroApp makes a data access request to the back-end data service server. The back-end server then validate this token with the identity provider to grant the access to the data requested.

Page 15 of 88 MicroApps Technical User Guide - Configuring a System Environment

This option fits to the On Premises System Configuration Scenario, where MicroApp server modules are administrated on the server on premise, since the MicroApp server modules are protected by this authentication option and data services are only accessed through the server modules.

For more details and examples for this SSO option, refer to Appendix - Single Sign-On Using Federated User Management.

SSO Using Signed Fetch

In the Hybrid System Configuration Scenario, MicroApp End User Environment and Management Environment are both hosted in the cloud, usually by the same third party vendor, therefore it does not require SSO between these two environments. However, SSO is required between the Management Environment and back-end data server environment, since back-end data servers are hosted on premises behind the firewall. Typically, in this scenario, the user data and access control are managed separately between the MicroApp End User and Management Environments and back-end data servers.

To establish SSO between the Management Environment and back-end data server environment, the OAuth standard with user credential mapping can be used, as long as it is supported by both environments. This mechanism is often called OpenSocial Signed Fetch or 2-legged OAuth.

This option fits to the Hybrid System Configuration Scenario, as long as MicroApp container modules and/or server modules are all administrated on the Management Environment hosted by third party vendors. Example of such Management Environment would be the Private Gallery supported in Google Apps.

For more details on this SSO option, refer to Appendix - Single Sign-On Using Signed Fetch.

SSO Using 3-Legged OAuth Authentication

OAuth protocol defines an authentication scheme where end-users can authorize an application running on an external system to grant an access to their back-end data for a fixed time period, e.g., couple of months, weeks or days. As result, the application receives credentials for an access to the back-end data for limited time, without ever knowing the end- user's identity at the back-end system.

Since the end-users are required to log in to their back-end system each time when the granted access is expired, OAuth may technically not be considered as a Single Sign-On solution, yet it serves the same purpose by minimizing the number of log-ins that the end-users are required to access the back-end data for a specific period of time.

The details of this SSO option will be included here as soon as it is available.

SSO Workaround

If any of the run-time environments does not support SAML, the following workarounds are available:

• Client Certificate X.509 client certificates are used for authenticating a user per Enterprise MicroApp.

• Master Login Enterprise MicroApp You can create a custom Enterprise MicroApp and place it on the Enterprise MicroApp container to let users log on manually once, and then all other Enterprise MicroApps on the same container can share the login credential.

For more details on these workaround options, refer to Appendix - Single Sign-On Workaround.

Page 16 of 88 MicroApps Technical User Guide - Developing an Enterprise MicroApp Developing an Enterprise MicroApp

Contents

• Back-end Development • Front-end Development

Back-end Development

Back-end development includes creating a new data service or locating and/or enhancing an existing data service, and configuring it as a web service accessible by external applications. Back-end development is typically performed by developers who have knowledge of data processing functions and services at back-end enterprise systems. In order to configure a data service, e.g. for access-control, it is required to have an administrative account access to the server that hosts the data service.

What is Data Service?

Data services are hosted on a server located on premises and enable reading and/or writing data from back-end enterprise systems. Data services access back-end data via calling functions and services provided by back-end SAP systems, e.g. RFCs, Enterprise Services, and provide required data in the JSON or XML format.

Examples of the data services:

• SAP Enterprise Services located at ES Workplace • Web service generated out of SAP RFC Function Module • Composite Application Service (a.k.a. CAF Service) built on SAP NW Composite Environment

Creating and Configuring Data Service

If there is no existing data service to fulfill the Enterprise MicroApp requirements, a new data service can be created. A new data service can be created from an existing SAP RFC Function Module without any additional coding, as long as the RFC fulfills the Enterprise MicroApp requirements. Please refer to the SAP Help for more details.

If a new data service is calling multiple back-end functions and services, you can develop an SAP Composite Application Service using SAP NetWeaver Developer Studio (NWDS). The generic procedure to create an SAP SAP Composite Application Service as a data service is as follows:

1. Creating a project on NWDS 2. Importing necessary RFCs 3. Mapping attributes of imported RFCs' input and output parameters 4. Writing data mash up logic 5. Exposing it as a web service 6. Testing the web service

After creating a data service, it must be configured on the server. This section explains configuring a data service using SAP NetWeaver Administration tools. The generic procedure is as follows:

1. Configuring a target system for back-end function call 2. Configuring the security setup

You can find detailed step-by-step instructions for creating and configuring sample data services in MicroApplications Samples page.

Page 17 of 88 MicroApps Technical User Guide - Developing an Enterprise MicroApp Front-end Development

Front-end development includes creating an Enterprise MicroApp front-end modules that consume data services described above and provide user interface, user interaction handling and process flow control functions, therefore is typically performed by developers with UI design knowledge. Depending on the choices of MicroApp containers, there are varieties of the MicroApps that you can develop.

The following MicroApp types are described in this section:

• Browser iFrame-base Enterprise MicroApp • Browser OpenSocial Enterprise MicroApp • Mobile Enterprise MicroApp • Desktop Enterprise MicroApp

Browser iFrame-Base Enterprise MicroApp Development

This type of MicroApps is a good choice if you have multiple MicroApp containers to support, but want to keep the main part of the front-end modules in a single place. You can develop a MicroApp server module as a central part which provisions the UI control and data access logic, then build container specific module which acts as a wrapper of the server module and offers some container functionalities, such as user preference handling.

Examples of such MicroApps include:

• Google URL-Type Gadget • Netvibes Web Page Widget • or any widgets and gadgets run in containers that support iFrame html tag

For more details of how to develop and deploy this type of MicroApps, please see Appendix - iFrame-base Enterprise MicroApp Development

Browser OpenSocial Enterprise MicroApp Development

As a variation of the browser Enterprise MicroApps, you can develop only the container module, and using API functions and services that are offered by the container server you can call data services to access the back-end data directly from the container module. This type of Enterprise MicroApps usually requires the Hybrid configuration scenario described in the previous section of this document.

Some of the MicroApp containers that support OpenSocial standard, e.g. GoogleApps, offer administrative features of deployed MicroApps for IT professionals of enterprise. However, it does not fit your security need, or the container does not offer any administrative features, you can choose one of the advanced security options based on OAuth. With this option, the definition of each Enterprise MicroApp (server module) is registered and administrated at a server on premise by the IT professionals. More details of the OAuth base security options are described in Configuring a System Environment.

Examples of OpenSocial Enterprise MicroApps include:

• Google OpenSocial Gadget • or any widgets and gadgets run in containers that support OpenSocial standard

For more details on OpenSocial container module development topics, please refer to Appendix - OpenSocial Enterprise MicroApps Development.

Mobile Enterprise MicroApp Development

Mobile Enterprise MicroApps are deployed and run on an end user's mobile device. Such MicroApps are developed using native platforms and API functions and services offered by the mobile device software. Since these MicroApps are installed on the end user's mobile device and accessing the back-end data by calling directly data services, it is typically required to create only the Enterprise MicroApp container modules.

Page 18 of 88 MicroApps Technical User Guide - Developing an Enterprise MicroApp iPhone Native-App

The iPhone Native-App development process should follow the standard iPhone development patterns and APIs that are well covered on iPhone Developer Center web pages.

As for other Enterprise MicroApps, for back-end data access iPhone application has to call data services. Surprisingly, iPhone SDK doesn't provide out-of-box solution for consuming SOAP web services, but it still is possible to implement data access by implementing SOAP communication paradigms from scratch in code. There are number of articles covering WebService integration with iPhone application, including article on iCode blog and article on Omniture Developer Connection.

For more specific information on iPhone Native-App development development, please refer to Appendix - iPhone Enterprise MicroApps Development.

Other mobile device applications

For more information on other mobile device application development and sample codes, please refer to SDN Wiki page.

Desktop Enterprise MicroApp Development

Desktop Enterprise MicroApps are deployed and run on an end user's desktop. Such MicroApps are developed using native platforms and API functions and services offered by the desktop software. Since these MicroApps are installed on the end user's desktop and accessing the back-end data by calling directly data services, it is typically required to create only the Enterprise MicroApp container modules.

For more details on desktop container module development topics, please refer to Appendix - Desktop Enterprise MicroApps Development.

Page 19 of 88 MicroApps Technical User Guide - Appendix - Firewall Traversal Appendix - Firewall Traversal

Contents:

• Reverse Proxy • Other Solutions

Reverse Proxy

"Reverse Proxy" or "Application Gateway" is a proxy server located between the Internet and a private corporate network. A reverse proxy dispatches in-bound network traffic to a set of servers, presenting a single interface to the caller. For example, a reverse proxy could be used for load balancing a cluster of web servers.

Advantages of using reverse proxy or application gateway are:

• Increased security by introducing another firewall layer with HTTP level firewalling • Single point of access by client to multiple internal resources, hiding internal application server topology from the outside world • Increased performance by optional load balancing

See SAP Note 833960 - supported Application Gateway Configurations for a reference.

SAP Web Dispatcher

SAP Web Dispatcher is SAP system for providing single secure entry point for access to SAP ABAP and Java systems. The pros of SAP Web Dispatcher is tight integration with SAP Application Server systems providing increased security and accessibility. On a cons side is that SAP Web Dispatcher works only with SAP Application Servers - if there is existing non-SAP infrastructure, other reverse proxy solution should be considered. One of solutions in such case is reverse proxy chaining, where 3rd party reverse proxy is the first external entry point, with SAP related requests forwarded to SAP Web Dispatcher.

The following table describes SAP Web Dispatcher related information:

SAP Web Dispatcher related information Item Reference The SAP Web Dispatcher support http://help.sap.com/saphelp_nwce10/helpdata/en/42/5cfd3b0e59774ee10000000a114084/ page frameset.htm SAP Wiki page on Web http://wiki.sdn.sap.com/wiki/display/SI/Web+Infrastructure Infrastructure External "How-to" doc http://debasis.panda.tripod.com/sitebuildercontent/sitebuilderfiles/How_to_Configure_ SAPWebdispatcher.doc

Third Party Reverse Proxy

There is number of 3rd party software and hardware solutions providing reverse proxy or application gateway functionality, with variety of features provided by each. The choice of implementation to use depends on Enterprise current infrastructure, available expertise and specific needs.

Here are a few links covering some available solutions:

Reverse proxy solutions related information Item Reference SDN WIKI page on Proxy troubleshooting http://wiki.sdn.sap.com/wiki/display/BSP/Using+Proxies SDN Reverse Proxy Series blog by Alon Weinstein https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/1128

Page 20 of 88 MicroApps Technical User Guide - Appendix - Firewall Traversal Other Solutions

Google Secure Data Connector

Secure Data Connector (SDC) is offered by Google and enables applications hosted on the Google sites to access data and services that reside behind the firewall. More details can be found at http://code.google.com/securedataconnector/.

Details on how to install and configure Google Secure Data Connector are owned by Google Inc. Reference sites on Google are as follows (may require an user-account to login):

Reference sites on Google Item Reference SDC deployment https://sites.google.com/a/google.com/enterprise-gadgets-and-feeds-preview/secure- data-connector-deployment-preview-relee-v5 Secure Data Connector Developer's Guide http://code.google.com/securedataconnector/docs/overview.html Gadgets remote content http://code.google.com/apis/gadgets/docs/remote-content.html

Page 21 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development Appendix - iFrame-base Enterprise MicroApp Development

Contents:

• iFrame-Based Enterprise MicroApps • ° What is Container Module? ° What is Server Module? ° Creating and Configuring iFrame-base Server Module ° - Recommended Application Structure - iFrame-base Server Module Implementation details ° Creating and Configuring iFrame-base Container Module ° - Google URL Type Gadget - Netvibes Web Page Widget iFrame-Based Enterprise MicroApps iFrame-based Micro Applications are small applications that are shown to the user through a standard browser inline frame known as iFrame in HTML. Even though each HTML browser platform has its own specifics, use of HTML allows such Micro Applications to be extremely portable across variety of platforms and devices.

For this type of Enterprise MicroApp, the following two components are developed in general:

• Enterprise MicroApp container module which acts as a wrapper of the server module. • Enterprise MicroApp server module which provisions the UI control and data access logic

What is Container Module?

An Enterprise MicroApp container module is a component that is deployed on to its container, where end users can browse available MicroApps and choose the ones that fulfill their requirements. A container module provides end users with information about the MicroApp, such as name, author, version, and brief description of its functionalities. It also offers end-user preferences to personalize the functionalities and look-and-feel. Typically the container modules are built using the container specific functionality, therefore it is third party specific. Some of the MicroApp containers offer administrative features for the deployed MicroApps, such as a private gallery space, where IT professionals can register and group the MicroApps according to the targeted user groups.

What is Server Module?

An Enterprise MicroApp server module is an optional component that is deployed on the server on premise, where IT administrator can manage an access control of the MicroApp. The server module could be built in a way that absorbs third party container specific implementations and provisions different variations of the user interface and interaction logic per MicroApp container.

Creating and Configuring iFrame-base Server Module

The server module can be built and deployed as a standard J2EE application and hosted on the server on premise. For more details and step-by-step instructions of creating and deploying an iFrame-Based Server Module as a J2EE application based on SAP NetWeaver, please refer to the detailed how-to section at MicroApplications Samples page. For browser iFrame-base MicroApps, although the server modules are deployed and hosted on the server on premise, in order to support asynchronous data access, it provisions the main UI control and data access logic to the container module, which is typically programmed in a scripting language, such as JavaScript, and downloaded and executed on the client browser.

Page 22 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

Recommended Application Structure

An Enterprise MicroApp Server Module is built using standard HTML, and in order to support asynchronous data access, the main UI control and data access logic is coded in JavaScript.

The JavaScript coding follows the Model View Controller (MVC) architecture, where MVC is both a design pattern and an architectural pattern used in the software engineering. MVC isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. For more information on MVC, see http://en.wikipedia.org/wiki/Model-view- controller and http://www.enode.com/x/markup/tutorial/mvc.html.

The following diagram displays the recommended Enterprise MicroApp file and folder structure:

Enterprise MicroApp file and folder structure

The following table explains Enterprise MicroApp files:

File Description Model.js The WebContent\js\Model.js file holds the data request and sending functionality. It prepares the request to be sent, handles a response, and parses the response data. View.js The WebContent\js\View.js file defines the logic of displaying an Enterprise MicroApp on the screen and manages the Enterprise MicroApp UI. Controller.js A controller represents the Enterprise MicroApp logic. The WebContent\js\ Controller.js file describes all actions that can be performed in the UI with a widget, such as reaction on the button click or finished data loading. Utils.js The WebContent\js\Utils.js file describes the general purpose of utility functions. It supports fetching data from and sending to remote servers using the standard XMLHttpRequest request or any third party function provided in the Enterprise MicroApp or gadget Application Programming Interface (API), for example, makeRequest. *.jsp,*.html The *.jsp, *.html file contains the script to include *.js and *.css files and HTML elements that determine the appearance of the gadget, and the script to include gadget API libraries.

Page 23 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development iFrame-base Server Module Implementation details

The HTML and/or JavaScript implementations may have some variations depending on which Enterprise MicroApp containers are supported, and which container specific functionalities are supported. The server module can be developed in a way that absorbs such variations of implementations. The section shows you some sample implementations.

• Sample MicroApplication Overview • Process Flow • Core Functionality Implementation ° HTML Code Sample ° Platform Specific Libraries Inclusion Code Sample ° Data Service Call Code Sample ° User Settings Code Sample ° Height Adjustment Code Sample • Configuration

Sample MicroApplication Overview

The sample MicroApp that is described in this section uses "User Lookup" data service, which is to find user's first and last name by user's login id.

Application contain two screens. On first screen user enters a username and presses Go to start search process.

Then microapp executes web service to get required data and shows second screen with first and last name of entered user.

All code snippets described below are included in the iFrame-base MicroApp samples at the detailed how-to section at MicroApplications Samples page.

Process Flow

This section contain flow diagrams that describe User Lookup MicroApp sample.

MicroApp Loading Process iFrame-Based micro application loading process.

Page 24 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

Page 25 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

Data Request Process

Data request process for iFrame-Based micro application.

Core Functionality Implementation

HTML Code Sample

In HTML code, you can include container-specific libraries, as seen in the sample code below.

User Lookup

Page 27 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

First name:

Last name:

Since recommended approach is to put more functionality on client side using dynamic DOM manipulation, usage of some JavaScript framework for DOM manipulation is highly recommended. In our sample we are using jQuery that is proven as mature and reliable library for cross-browser development - see jQuery documentation pages for more details on features supported by this library.

Third party javascript files can be either linked from a third party source or copied and placed in this application structure, e.g., under WebContent\js\ext\some.3rd.party.js. Our sample UserLookup Enterprise MicroApp uses the jQuery javascript library linked directly from jQuery site:

... ...

Platform Specific Libraries Inclusion Code Sample

Sample above has iGoogle specific code for reading container specific libraries provided by iGoogle container in url attribute "libs". Libraries provided must be included in order for MicroApplication to use container specific APIs.

Similar approach may be used in other containers as well.

Data Service Call Code Sample

This section explains calling data services using the XMLHttpRequest request. The XMLHttpRequestrequest is a DOM API that can be used by JavaScript and other web browser scripting languages to transfer XML and other text data between a web server and a browser. For more information on the XMLHttpRequest request, see http:// en.wikipedia.org/wiki/XMLHttpRequest, http://www.w3.org/TR/XMLHttpRequest/, and http://msdn.microsoft.com/en-us/ library/ms535874(VS.85).aspx. For simplicity, developers can use third party wrappers for AJAX calls. In the example below, the jQuery AJAX method is used. By default jQuery uses "$" namespace to group all jQuery specific function, so ajax functions call on jQuery would look as follows:

$.ajax({... function specific parameters.... })

For more information on jQuery please refer to http://jquery.com/

To call a data service, proceed as follows:

1. In the Utils.js file, create a utils object as follows:

utils = {};

2. To implement logic of posting data to the server, create utils.doPost. It is recommended to create a wrapper of this method to allow easier transition between different containers, where each can have specific methods for data loading. In this example, a direct AJAX call to backend supported by the jQuery AJAX call function ($.ajax):

/** * The utils function to request data * @param {String} url - request destination * @param {Object} data - data to send * @param {Function} callbackFunction - function to call on request complete. * @return if request finished seccessfuly, return response string, else calls error handling function */ utils.doPost = function(/** String */ url, /** Object */ postXML, /** Function */ callbackFunction){ // notify model that data loading is about to start Model.onStartLoading();

// Perform data request using jQuery AJAX API $.ajax({ type: "POST", contentType: "text/xml", url: url, data: postXML, dataType: "xml", success: function(aData, textStatus) { // notify model that data loading is successfully finished Model.onSuccessLoading(); // call callbackFunction providing data retured from web service callbackFunction(aData); }, error: function(XMLHttpRequest, textStatus, errorThrown) {

Page 29 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

// notify model that data loading failed Model.onFailLoading(textStatus); } }); }

3. To invoke actual data post, invoke utils.doPost method. Since we need to ensure that server in SOAP body receives valid XML document, we need to create a helper function for escaping string literal values to valid XML data:

utils.xmlencode = function(/** String */ string) { if ( !string ) { return ''; } return string.replace(/\&/g,'&'+'amp;').replace(//g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;'); }

Now we can do actual invocation of the call. For making request to server, developer must know the XML structure of SOAP request and response. Convenient way to find it out is to use Web Services Navigator in test mode. Web Services Navigator is SAP WebAS tool to discover and invoke web services, accessible via http://: > Web Services Navigator. Below is the sample coding in Model.js for calling User Lookup data service:

Note that endpoint has relative URL as web application is not allowed to perform web service call via AJAX from different domain due to Cross-Site scripting restrictions. That means that either web service and web application should be deployed on same host, or reverse proxy should be used for serving web service and micro-application to end user.

Model.getUserDetails = function(/* String */ sUserId, /* Function */ fSuccessCallback ){ // Define Web Service URL. var url = "/UserLookupWS/UserLookupService"

// Define application logic to be performed when data from server is received. Using Web Services Navigator, // we know that response will have XML fields: pns:firstName and pns:lastName that can be easily read using // jQuery API and return data to controller as fields of "userData" object var callbackFunction = function(aData){ var userData = { "user_firstname":$(aData).find('ns2\\:firstName').eq(0).text(), "user_lastname":$(aData).find('ns2\\:lastName').eq(0).text() } fSuccessCallback(userData); };

// Define SOAP message to be sent to be send to the server // Most convenient is just to define as a string literal with all required headers coded in var postXML = '' +'' +' ' +' ' +' true' +' ' +' ' +' ' +' ' // on next line we specify parameter to SOAP WS call provided by the application user // we use xmlencode function to make sure all string literals are correctly escaped +' ' + utils.xmlencode(sUserId) + ''

Page 30 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

+' ' +' ' +'';

//make post request using utility class utils.doPost(url,postXML,callbackFunction); }

Note for Google Gadgets container: Google Gadgets are built using Google Gadget technologies. (For information on Google Gadget, see http:// code.google.com/apis/gadgets/docs/dev_guide.html.) Even though the Google container is an OpenSocial container, per OpenSocial specification, the OpenSocial method gadgets.io.makeRequest is not available for Google URL Type Gadgets. (Google URL Type Gadget is one of the Gadget content types supported by Google. For more details on the Gadget content type, see http://code.google.com/apis/gadgets/docs/fundamentals.html#Content_Type.) Hence the only option is to use XMLHttpRequest and the sample code above for Data Service call is applicable for Google URL Type Gagdet.

User Settings Code Sample

Some MicroApp containers may support end-user preference setting per MicroApp. In this case the MicroApp container usually provides guidelines and APIs for implementing accessing the preference setting for MicroApp developers.

Below is a sample for implementing the preference setting access in Google container.

Note: it is recommended to create wrapper functions over container specific API as in samples below to ensure code is easily adjustable to various containers.

For using the preference related API, you need to add "setprefs feature" in your Google Gadget container module (i.e. definition xml).

Then, you will be able to use the preference related API (i.e. _IG_Prefs class).

utils.prefs = { "getLastSearch" : function(){ // if iGoogle specific APIs exists for getting value, use it if(typeof _IG_Prefs != "undefined"){ var prefs = new _IG_Prefs(); return prefs.getString("lastSearch"); }

// if some other container specific library exists - use it if(typeof mycontainer.settings != "undefined"){ return mycontainer.settings.getValue("lastSearch"); } }, "setLastSearch" : function(value){ if(typeof _IG_Prefs != "undefined"){ var prefs = new _IG_Prefs(); prefs.set("lastSearch", value ); return; }

if(typeof mycontainer.settings != "undefined"){ mycontainer.settings.setValue("lastSearch", value); return; } }

Page 31 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

}

Height-Adjustment Code Sample

Another common feature that is supported by some of the MicroApp containers is so called height-adjustment. With this feature, the container adjusts the vertical size of MicroApps to ensure the iFrame size is adequate to show the MicroApp content. As iFrame is isolated from the container, the height-adjustment is performed via the containers API.

Below is sample for implementing the height-adjustment in Google container.

For using the height-adjustment API, you need to add "dynamic-height feature" in your Google Gadget container module (i.e. definition xml).

Then, you will be able to use the height-adjustment API (i.e. _IG_AdjustIFrameHeight function).

utils.adjustIFrameHeight = function(){ // iGoogle specific APIs for updating frame height if (typeof _IG_AdjustIFrameHeight != "undefined"){ _IG_AdjustIFrameHeight("130px"); return; }

// Other platform if (typeof mycontainer!= "undefined"){ mycontainer.setWindowHeight("130px"); return; } }

Configuration

After creating a server module, it must be configured on the server to ensure a secure access to the module with appropriate authentication and authorization setting.

You can find more detailed information and step-by-step instructions of how to create and configure sample server modules at MicroApplications Samples page.

Creating and Configuring iFrame-base Container Module

Depending on the end-user environment there are varieties of container modules. In most of the Enterprise MicroApp containers, container modules are defined in XML format, specifying meta data of the application, such as name, version and author, as well as some proprietary features, such as personalization and auto height-adjustment.

There are several conceptual types of iFrame-base Container Module. The following iFrame-base container module types are presented in this section:

• Google URL Type Gadget • Netvibes Web Page Widget

Google URL Type Gadget

Google Apps Enterprise is used as the sample platform for web application based gadgets with the URL type content. For more information on Google Gadgets Content types, see

Page 32 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development http://code.google.com/apis/gadgets/docs/fundamentals.html#Content_Type. When a gadget has the URL content type, the href attribute provides URL, and any other content of the gadget specification is ignored. With the URL content type, all information related to the gadget UI and programmatic logic is settled in the file referenced by the URL. No HTML markup or JavaScript is required within the gadget itself.

Sample Implementation

The sample of a URL type gadget follows:

Gadgets of the URL type specify only a base URL. The standard set of parameters is added to this URL by the gadget server, which renders the gadget in the IFRAME. Gadgets of the URL type cannot take advantage of all features, especially features that manipulate HTML and JavaScript code directly. The URL gadget type is useful for converting existing web sites or applications into gadgets.

To define the URL type gadget similar to the HTML type gadget, the XML definition is used. The gadget XML definition main parts follows:

• gadget preferences section The section specify gadget characteristics such as title, author, require feature. For more information on the section, see http://code.google.com/apis/gadgets/docs/reference.html#Moduleprefs_Ref • user preferences section The section defines controls that allow users specifying gadget settings. For more information on the section, see http://code.google.com/apis/gadgets/docs/basic.html#Userprefs. An example of the section parameters follows:

By default, the datatype parameter is a string, and the code can be presented without the datatype parameter as follows:

User preferences can be accessed from the gadget using the user preferences JavaScript API. The following code is an example on how to access user preferences using JavaScript API:

var prefs = new_IG_Prefs(); var myNameStringPref = prefs.getString("myname"); var ageIntPref = prefs.getInt("intMyAge"); var singleBoolPref = prefs.getBool("boolPrefSingle"); alert("Hello "+ myName +"\n Age: "+ ageIntPref +"\n Single: "+ singleBoolPref);

• content section In the section, the type of the gadget, the URL type for the web application based gadgets, programming logic, and HTML parameters, which determine the gadget appearance, are specified. For more information on the section, see http://code.google.com/apis/gadgets/docs/reference.html#Content_Ref. The gadget content is a remote web page referenced by a URL in the gadget specification. The URL type gadget API is based on the IG...* * namespace. If gadget is developed for environment, which do not support gadgets.API, the

Page 33 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

URL type gadget API must be used. The gadgets. API currently works only in the OpenSocial containers. The _IG API allows adding various UI elements to the gadget, such as the dynamic height element.

Platforms Specific Functions and References

To use platform specific functions application must include libraries provided by iGoogle container in runtime using libs parameter. libs parameter. For detailed information on how libs parameter works refer to Google Gadgets Development Fundamentals For code snipped for including platform specific libraries refer to Platform Specific Libraries Inclusion Code Sample

When container specific libraries are included, micro application can use additional API to perform actions such as operations with application settings, resizing window height, updating gadget title and others.

For samples using iGoogle specific APIs see

• User Settings Code Sample • Height Adjustment Code Sample

For more information on the iGoogle specific API, see http://code.google.com/apis/gadgets/docs/legacy/dev_guide.html.

Deploying/Publishing URL Type Gadgets

URL type gadgets are specified in the XML format. The gadget file must be accessible from the Internet without the user authentication. Recommended hosting options are as follow:

Hosting as a part of the server module

In this case, deployed on a server on premise, e.g. NetWeaver In this case, the server module deployed on a server on premise and the security setting must be configured to bypass authentication for the gadget definition file. Below steps are based on NetWeaver as a server on premise:

1. In NetWeaver Development Studio, open the web.xml project file for editing and select the Security tab. 2. Add the Security Constraints entry, e.g., Public

3. Select the Web Resouce Collection tab, expand and navigate to Web Resource Collections > WebResource > URL patterns.

Page 34 of 88 MicroApps Technical User Guide - Appendix - iFrame-base Enterprise MicroApp Development

4. Add the pattern: /_widget_definition_file_name.xml

5. Do not specify any authentication constraint in the Auth Constraint tab, so that access to the resource is not protected by the login

Hosting on Google.

For this option Google Gadgets Editor (GGE) should be used. GGE is a tool for quick gadgets edit, save, host, and publish gadgets. For more information on GGE, see http://code.google.com/apis/gadgets/docs/legacy/gs.html#GGE.

Netvibes Web Page Widget

Netvibes provides support of publishing any web page as micro application on netvibes container using Web Page widget. Using this widget allows rendering iFrame-base Enterprise MricoApp inside netvibes platform, but, comparing to Google Type URL gadgets does not provide access to netvibes specific APIs, such as user settings or height adjustments.

To use Web Page Widget proceed as follows:

1. Open Netvibes Homepage 2. Add Web Page Widget to homepage by selecting "Add Content" -> "Essential Widgets" -> "Web Page"

3. After widget is added, configure it specifying iframe url, height and title:

4. Save changes to run microapplication

Page 35 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development Appendix - OpenSocial Enterprise MicroApp Development

Contents:

• OpenSocial Enterprise MicroApps • ° Google OpenSocial Gadget • Creating and Configuring OpenSocial Gadget • ° Recommended Application Structure ° OpenSocial Implementation details ° - Sample MicroApplication Overview - Process Flow - - MicroApp Loading Process - Data Request Process - Core Functionality Implementation - - Gadget Definition Sample - Platform Specific Libraries Inclusion Code Sample - Data Service Call Code Sample - User Settings Code Sample - Height-Adjustment Code Sample - Configurations

OpenSocial Enterprise MicroApps

Google OpenSocial Gadget

OpenSocial API is a set of common APIs for the web based social network applications. Applications implementing the OpenSocial APIs are interoperable with any social network site that supports them.

Choosing an API

For more information on OpenSocial API, see: http://code.google.com/apis/opensocial/docs/0.8/spec.html#overview, http://code.google.com/apis/opensocial/docs/0.8/devguide.html There are a few containers that support OpenSocial. For more information on various social networks, see: http://wiki.opensocial.org/index.php?title=Main_Page#Container_Information.

Creating and Configuring OpenSocial Gadget

OpenSocial Gadgets are specified in XML. Gadget XML can be edited in any text editor or in Google Gadgets Editor (GGE). GGE is a web-tool for quick gadgets edit, save, host, and publish gadgets. For more information on GGE, see http://code.google.com/apis/gadgets/docs/legacy/gs.html#GGE. There are some other third party development tools to create an OpenSocial Gadget, such as Eclipse based OpenSocial Development Environment (OSDE).

Page 36 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

OpenSocial Gadgets can be deployed and hosted on the server on premise, or in public hosting. In both scenarios gadget definition must be unprotected for OpenSocial container to be able to load gadget definition as well as other gadget resources, such as images, css/javascript files and other.

When deployed and running inside container all data requests are performed container API trough container server. Gadget is able to call any web service, including those that are deployed outside gadget hosting - no cross site scripting applies.

Recommended Application Structure

An Enterprise MicroApp Server Module is built using gadget definition XML, and in order to support asynchronous data access, the main UI control and data access logic is coded in JavaScript.

The JavaScript coding follows the Model View Controller (MVC) architecture, where MVC is both a design pattern and an architectural pattern used in the software engineering. MVC isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. For more information on MVC, see http://en.wikipedia.org/wiki/Model-view- controller and http://www.enode.com/x/markup/tutorial/mvc.html.

The following table explains OpenSocial Gadget files used:

File Description Model.js The WebContent\js\Model.js file holds the data request and sending functionality. It prepares the request to be sent, handles a response, and parses the response data. View.js The WebContent\js\View.js file defines the logic of displaying an Enterprise MicroApp on the screen and manages the Enterprise MicroApp UI. Controller.js A controller represents the Enterprise MicroApp logic. The WebContent\js\ Controller.js file describes all actions that can be performed in the UI with a widget, such as reaction on the button click or finished data loading. Utils.js The WebContent\js\Utils.js file describes the general purpose of utility functions. It supports fetching data from and sending to remote servers using the standard XMLHttpRequest request or any third party function provided in the Enterprise MicroApp or gadget Application Programming Interface (API), for example, makeRequest. *.xml The *.xml file contains gadget definition and includes *.js and *.css files and HTML elements that determine the appearance of the gadget.

OpenSocial Implementation details

OpenSocial gadget implementation is based on OpenSocial API. The section shows you some sample implementations of commonly used actions.

• Sample Enterprise MicroApp Overview • Process Flow • Core Functionality Implementation ° Gadget Definition Sample ° Platform Specific Libraries Inclusion Code Sample ° Data Service Call Code Sample ° User Settings Code Sample ° Height Adjustment Code Sample • Configurations

Sample MicroApplication Overview

The sample MicroApp that is described in this section uses "User Lookup" data service, which is to find user's first and last name by user's login id.

Application contain two screens. On first screen user enters a username and presses Go to start search process.

Page 37 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

Then microapp executes web service to get required data and shows second screen with first and last name of entered user.

All code snippets described below are included in the OpenSocial MicroApp samples at MicroApplications Samples page

Process Flow

This section contain flow diagrams that describe User Lookup microapp sample.

MicroApp Loading Process iFrame-Based micro application loading process.

Page 38 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

Data Request Process

Data request process for iFrame-Based micro application.

Page 39 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

Core Functionality Implementation

Gadget Definition Sample

In HTML code, you can include container-specific libraries, as seen in the sample code below.

Page 40 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

First name:
Last name:
]]>

Since recommended approach is to put more functionality on client side using dynamic DOM manipulation, usage of some JavaScript framework for DOM manipulation is highly recommended. In our sample we are using jQuery that is proven as mature and reliable library for cross-browser development - see jQuery documentation pages for more details on features supported by this library.

Third party javascript files can be either linked from a third party source or copied and placed in this application structure, e.g., under WebContent\js\ext\some.3rd.party.js. Our sample UserLookup Enterprise MicroApp uses the jQuery javascript library linked directly from jQuery site:

...

Page 41 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

...

Platform Specific Libraries Inclusion Code Sample

In order to use OpenSocial API MicroApplication must define it's usage in gadget definition as follows:

Data Service Call Code Sample

This section explains calling data services using the OpenSocial API.

To call a data service, proceed as follows:

1. In the Utils.js file, create a utils object as follows:

utils = {};

1. To implement logic of posting data to the server, create utils.doPost method as follows:

/** * The utils function to request data * @param {String} url - request destination * @param {Object} data - data to send * @param {Function} callbackFunction - function to call on request complete. * @return if request finished seccessfuly, return response string, else calls error handling function */ utils.doPost = function(/** String */ url, /** Object */ postXML, /** Function */ callbackFunction){ // notify model that data loading is about to start Model.onStartLoading();

// Perform data request using Open Social API var params = {}; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT; params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST; params[gadgets.io.RequestParameters.POST_DATA] = postXML ; params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 1; params[gadgets.io.RequestParameters.HEADERS] = { "Content-Type" : "text/xml; charset=utf-8" }; //make request gadgets.io.makeRequest(url, function(responseObj){ if ( typeof responseObj.text != 'undefined' && responseObj.rc == 200 ) { // notify model that data loading is successfully finished Model.onSuccessLoading(); callbackFunction(responseObj.text); } else { // notify model that data loading failed Model.onFailLoading(responseObj.responseText); }

Page 42 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

}, params); }

2. To invoke actual data post, invoke utils.doPost method. Since we need to ensure that server in SOAP body receives valid XML document, we need to create a helper function for escaping string literal values to valid XML data:

utils.xmlencode = function(/** String */ string) { if ( !string ) { return ''; } return string.replace(/\&/g,'&'+'amp;').replace(//g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;'); }

Now we can do actual invocation of the call. For making request to server, developer must know the XML structure of SOAP request and response. Convenient way to find it out is to use Web Services Navigator in test mode. Web Services Navigator is SAP WebAS tool to discover and invoke web services, accessible via http://: > Web Services Navigator. Below is the sample coding in Model.js for calling User Lookup data service:

Model.getUserDetails = function(/* String */ sUserId, /* Function */ fSuccessCallback ){ // Define Web Service URL. var url = "http://[host:port]/UserLookupWS/UserLookupService"

// Define application logic to be performed when data from server is received. Using Web Services Navigator, // we know that response will have XML fields: pns:firstName and pns:lastName that can be easily read using // jQuery API and return data to controller as fields of "userData" object var callbackFunction = function(aData){ var userData = { "user_firstname":$(aData).find('ns2\\:firstName').eq(0).text(), "user_lastname":$(aData).find('ns2\\:lastName').eq(0).text() } fSuccessCallback(userData); };

// Define SOAP message to be sent to be send to the server // Most convenient is just to define as a string literal with all required headers coded in var postXML = '' +'' +' ' +' ' +' true' +' ' +' ' +' ' +' ' // on next line we specify parameter to SOAP WS call provided by the application user // we use xmlencode function to make sure all string literals are correctly escaped +' ' + utils.xmlencode(sUserId) + '' +' ' +' ' +'';

//make post request using utility class utils.doPost(url,postXML,callbackFunction);

Page 43 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

}

User Settings Code Sample

Some MicroApp containers may support end-user preference setting per MicroApp. In this case the OpenSocial container provides guidelines and APIs for implementing accessing the preference setting for MicroApp developers.

Below is a sample for implementing the preference setting access in Google container.

Note: it is recommended to create wrapper functions over container specific API as in samples below to ensure code is easily adjustable to various containers.

For using the preference related API, you need to add "setprefs feature" in your Google Gadget container module (i.e. definition xml).

Then, you will be able to use the preference related API (i.e. gadgets.Prefs class).

/** * The utils function for getting and setting preferences */ utils.prefs = { "getLastSearch" : function(){ // check if OpenSocial API is available if(typeof gadgets != "undefined"){ var prefs = new gadgets.Prefs(); return prefs.getString("lastSearch"); } }, "setLastSearch" : function(value){ // check if OpenSocial API is available if(typeof gadgets != "undefined"){ var prefs = new gadgets.Prefs(); prefs.set("lastSearch", value); } } }

Height-Adjustment Code Sample

Another common feature that is supported by some of the MicroApp containers is so called height-adjustment. With this feature, the container adjusts the vertical size of MicroApps to ensure the iFrame size is adequate to show the MicroApp content. As iFrame is isolated from the container, the height-adjustment is performed via the containers API.

Below is sample for implementing the height-adjustment in OpenSocial container.

For using the height-adjustment API, you need to add "dynamic-height feature" in your OpenSocial container module (i.e. definition xml).

Then, you will be able to use the height-adjustment API (i.e. gadgets.window.adjustHeight function).

Page 44 of 88 MicroApps Technical User Guide - Appendix - OpenSocial Enterprise MicroApp Development

/** * The utils function to resize gadget in iframe */ utils.adjustIFrameHeight = function(){ // check if OpenSocial API is available if (typeof gadgets != "undefined"){ gadgets.window.adjustHeight("130px"); } }

Configurations

As an Enterprise MicroApp container for the OpenSocial Gadget, Google Apps and Sites offers some administrative tools, such as Private Gadget Editor and Domain Gadget Directory Manager, which allows IT professionals to configure a private Enterprise MicroApp gallery space. For more information on Private Gadget Administration, see http://code.google.com/p/google-feedserver/wiki/ PrivateGadgetAdministratorsGuide.

Page 45 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development Appendix - Desktop Enterprise MicroApp Development

This section introduces developing and deploying the Enterprise MicroApps Container Module.

Contents:

• Creating Desktop Enterprise MicroApps • ° Recommended Application Structure ° Desktop MicroApp Implementation details ° - Sample MicroApplication Overview - Process Flow - - MicroApp Loading Process - Data Request Process - Core Functionality Implementation - - Gadget Definition Sample - Data Service Call Code Sample - User Settings Code Sample

Creating Desktop Enterprise MicroApps

Desktop Enterprise MicroApplications are running on end-user's desktop and relying on a desktop engine as MicroApp container which is provided by third party vendor to render MicroApplication UI and support a connectivity to back-end systems.

Examples of the desktop MicroApp containers are:

• Windows Sidebar • MacOS X Dashboard • Google Desktop • Yahoo! Widgets

Recommended Application Structure

A desktop MicroApp is usually defined in XML or HTML that acts as application starting point. In order to support asynchronous data access, the main UI control and data access logic is coded in lightweight scripting languages, such as JavaScript, using APIs that are usually specific to 3rd party vendor who provides the desktop engine.

The JavaScript coding follows the Model View Controller (MVC) architecture, where MVC is both a design pattern and an architectural pattern used in the software engineering. MVC isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. For more information on MVC, see http://en.wikipedia.org/wiki/Model-view- controller and http://www.enode.com/x/markup/tutorial/mvc.html.

The following table explains typical files used for Desktop Enterprise MicroApp implementation:

File Description Main.js The Main.js file is application starting point. It is used for setting event handler for UI components and initializing libraries. Model.js The Model.js file holds the data request and sending functionality. It prepares the request to be sent, handles a response, and parses the response data. View.js The View.js file defines the logic of displaying an Enterprise MicroApp on the screen and manages the Enterprise MicroApp UI. Controller.js A controller represents the Enterprise MicroApp logic. The Controller.js file describes all actions that can be performed in the UI with a widget, such as reaction on the button click or finished data loading. Utils.js The Utils.js file describes the general purpose of utility functions. It supports fetching data from and sending to remote servers using the standard XMLHttpRequest request or any third party function provided in the Enterprise MicroApp or gadget Application Programming Interface (API), for example, makeRequest.

Page 46 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development

File Description Note: Depending on application size and logic multiple utility classes/libraries may be used in project. *.xml,*.html,*.kon The *.xml file contains gadget definition and includes *.js and *.css files and HTML/XML elements that determine the appearance of the MicroApp.

Desktop MicroApp Implementation details

The section shows you some sample implementations of commonly used actions.

• Desktop Enterprise MicroApp Overview • Process Flow • Core Functionality Implementation ° MicroApp Definition Sample ° Data Service Call Code Sample ° User Settings Code Sample • Configurations

Sample MicroApplication Overview

The sample MicroApp that is described in this section uses an SAP Enterprise Service called "Business Partner Search", which is to find a business partners by a user's name.

Note: In this sample implementation, we are using Yahoo! Widgets engine as MicroApp container. All code snippets described below are included in a sample desktop MicroApp "Business Partner Search Yahoo Widget" at MicroApplications Samples page.

Application contain two screens. On first screen user enters a search phrase and presses enter to trigger search.

Then microapp executes web service to get required data and shows second screen with list of found business partners.

Page 47 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development

Process Flow

This section contain flow diagrams that describe Business Partner Search MicroApp sample.

MicroApp Loading Process

Desktop MicroApp initialization Process

Page 48 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development

Data Request Process

Data request process for Desktop MicroApp.

Page 49 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development

Core Functionality Implementation

Gadget Definition Sample

In XML code, you can include container-specific libraries, as seen in the sample code below.

mainWindow 500 300 left 255 1 0

feedbackWindow 1 1 topmost center

// printing widget information in debug console log(widget.name + " version is " + widget.version); log("Custom Template Release: "+XMLDOM.parse(filesystem.readFile("widget.xml")).evaluate("string(metadata/ templateVersion)"));

//Define the required utility files, platform dependent utilities for //working with windows, logging, debug, specific UI items, //and element functions. include("js/utils/PlatformUtil.js");

include("js/utils/DomUtil.js"); include("js/utils/CommonUtil.js"); include("js/utils/Common.js"); //timer function, used by the HTTP request class (DataLoader) include("js/utils/Timer.js"); //class for making HTTP requests include("js/utils/DataLoader.js"); //RFC request abstraction include("js/utils/RFCRequest.js"); //skin library include("js/skinlib/SkinLib_Include.js");

//The Main.js file contains widget initialization and creation code. include("components/Main/js/Main.js");

// saving state of demo mode log("Starting deployment");

Page 50 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development

// startupServices.startDeployment(function(){ log("Deployment Finished"); Main.load(); // });

Controller.onPreferencesChanged();

main SAP Settings SAPGroup.png PopupSearchMenu main Popup Search Menu true text WSURL main Web Services URL text http://crm.esworkplace.sap.com/sap/bc/srt/xip/sap/CRMXI_BPBASICDATABYNAMEADDRQR WSClient main Client text 800

Third party javascript files should be included in application bundle and linked to be used:

... //Define the required utility files, platform dependent utilities for //working with windows, logging, debug, specific UI items, //and element functions. include("js/utils/PlatformUtil.js");

include("js/utils/DomUtil.js"); include("js/utils/CommonUtil.js"); include("js/utils/Common.js"); //timer function, used by the HTTP request class (DataLoader) include("js/utils/Timer.js"); //class for making HTTP requests include("js/utils/DataLoader.js"); //RFC request abstraction include("js/utils/RFCRequest.js"); ...

Page 51 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development

Data Service Call Code Sample

This section shows data service call sample using the Desktop Platform API.

1. To implement logic of posting data to the server, create {{Model.postData }} method as follows: Note: Coding is using 3-rd party library utils.DataLoader to hide low-level HTTP POST implementation details.

/** *This function provide functionality for POST request * @param {String} requestURI request url * @param {String} postData data to be send * @param {Function} callback on success handler * @param {Function} failCallback on fail handler */ Model.postData = function(requestURI, postData, callback, failCallback ){ //show loading indicator Controller.handleStartLoading(); //read preference values var username = preferences.WSUsername.value var password = preferences.WSPassword.value //create headers to set for POST request var requestHeader = {}; requestHeader["Content-Type"] = "text/xml"; //check if authorization information is set in preferences if(utils.trim(username) != "" && utils.trim(password) != ""){ requestHeader["Authorization"] = Model.encodeBase64(username+":"+password) }

//Create an object DataLoader, that provides required parameters, //such as URI, for requesting data. var dataLoader = new utils.DataLoader( requestURI, { rawData : postData, //data to post method : "POST", // request type outputFormat : "text", // expected output format verbose: true, // display the debug retryCount : 10, // retry count blockingMode: false, // true for synchronous call headers : requestHeader //headers to send

}); // specify action on successful data response dataLoader.onLoad = function(data){ Controller.handleFinishLoading(); callback(data); }; //On unsuccessful data load caused by server connection or //timeout problems, specify the appropriate error message. dataLoader.onError = function(exception){ Controller.handleFinishLoading() failCallback("Exception happened: " + exception); }; //set error messages for known error codes returned by server dataLoader.onHandle = function(ResponseErrorCode){ Controller.handleFinishLoading() var errorMessage = "Unknown"; if(ResponseErrorCode == 500){ errorMessage = "Internal server error." }else if(ResponseErrorCode == 0){ errorMessage = "Failed to connect to backend systems." }else if(ResponseErrorCode == 401){ errorMessage = "The request requires user authentication." }else if(ResponseErrorCode == 404){ errorMessage = "File not found." }else if(ResponseErrorCode == 403){

Page 52 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development

errorMessage = "Access denied." } failCallback("Failed to get data.\nReason: "+errorMessage); }; //set handler for onTimeout event dataLoader.onTimeout = function(){ Controller.handleFinishLoading() failCallback("Request to backend systems have been timed out"); }; // start loading process dataLoader.loadData(); }

2. To invoke actual data post, invoke utils.doPost method. Since we need to ensure that server in SOAP body receives valid XML document, we need to create a helper function for escaping string literal values to valid XML data:

utils.xmlencode = function(/** String */ string) { if ( !string ) { return ''; } return string.replace(/\&/g,'&'+'amp;').replace(//g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;'); }

Now we can do actual invocation of the call. For making request to server, developer must know the XML structure of SOAP request and response. Convenient way to find it out is to use Web Services Navigator in test mode. Web Services Navigator is SAP WebAS tool to discover and invoke web services, accessible via http://: > Web Services Navigator. Below is the sample coding in Model.js for calling User Lookup data service:

//======/** *This function requests Partner data * @param {Object} partnerName partner name * @param {Function} callback on success handler * @param {Function} failCallback on fail handler */ Model.getBusinessPartnersData = function(partnerName, callback, failCallback){ //get host and client from preferences var url = ""+utils.trim(preferences.WSURL.value)+ "?sap-client="+utils.trim(preferences.WSClient.value) //SOAP to post var soapAction = '' +'' +'' +'' +'' +''+utils.xmlencode(partnerName.PARTNER)+'' +'' +'' +'' +'' //fatch partner data Model.postData(url, soapAction, function(response){ // on success var xmlDoc = XMLDOM.parse(response); Model.parseBusinessPartnerData(xmlDoc, callback)

Page 53 of 88 MicroApps Technical User Guide - Appendix - Desktop Enterprise MicroApp Development

}, // on fail failCallback) }

User Settings Code Sample

Some MicroApp containers may support end-user preference setting per MicroApp. In this case the Desktop Platform provides guidelines and APIs for implementing accessing the preference setting for MicroApp developers.

Below is a sample for implementing the preference setting access in Google container.

For using the preference related API, you need to add settings definition in your Yahoo Widget defenition (i.e. definition kon).

WSURL main Web Services URL text http://crm.esworkplace.sap.com/sap/bc/srt/xip/sap/CRMXI_BPBASICDATABYNAMEADDRQR

Then, you will be able to use the preference related API (i.e. preferences. class) as follows to access defined settins

var webServiceURL = preferences.WSURL.value;

Page 54 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development Appendix - iPhone Enterprise MicroApp Development

Introduction

This section serves as a user's guide for IT professionals and developers, and provides guidelines on developing an Enterprise MicroApps on the iPhone. It includes the following topics:

• Consuming SAP data from iPhone applications • Managing a secure web service calls • Ensuring an application quality with various development tools • Tips and Tricks for developing iPhone applications

General development topic are already covered by existing iPhone Development Documentation available under the following URL: https://developer.apple.com/iphone/library/documentation/Xcode/Conceptual/iphone_development.

This section covers more specific scenarios and tools that can be useful for developing iPhone applications and consuming SAP data from an iPhone application.

For more information about Enterprise MicroApplication development and code samples, please visit SAP Imagineering SDN wiki space.

Contents:

• Introduction • Using iPhone Application for Consuming SAP Data • ° General Information on Implementing Web Service Calls ° Implementing a SOAP Web Service Call ° - Building a SOAP Web Service Request and Calling a Web Service - Parsing a SOAP Web Service Response - Alternative Ways for Performing Web Service Call - Additional Information ° Implementing a REST/JSON Web Service Call ° - Web Service Interface - Building the REST Web Service Request and Calling a Web Service - Parsing the REST Web Service Response - Additional Information • Available Authentication Mechanisms • ° Supporting Basic Authentication ° Supporting a Client Certificate Authentication ° Supporting SAP Logon Ticket • Existing Development Documentation and Tools • ° Apple Standards and Guidelines ° Memory Management Recommendations ° Development Tools ° - Xcode - Code Analyzing Tools - Code Coverage Tools - Other Tools • Tips and Tricks • ° Controlling an Application Mode

Using iPhone Application for Consuming SAP Data

To call web services and consume SAP data, an iPhone application can use several types of web service protocols, such as SOAP or REST. This section represents information and example for calling both SOAP and REST web services from the iPhone application.

Page 55 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development General Information on Implementing Web Service Calls iPhone SDK provides several APIs for calling a web service via HTTP/HTTPS protocols. The NSURLConnection class is considered to be the most flexible method of downloading a URL contents. The class provides functionality for creating, managing connection, and controlling the connection flow.

For more information on the NSURLConnection class see the following links:

Resource Link iPhone Reference Library: Using NSURLConnection http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ URLLoadingSystem/Tasks/UsingNSURLConnection.html NSURLConnection Class Reference http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/ Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#/ /apple_ref/occ/cl/NSURLConnection iPhone Reference Library: URL Loading System http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ URLLoadingSystem/Concepts/URLOverview.html

Implementing a SOAP Web Service Call

SOAP is one of Web Service implementation protocols that is commonly used in Enterprise Applications and can be consumed by an iPhone application. SOAP uses XML as the request/response representation format. To call a web service, a developer must create a data request xml, POST it to a web service URL, and parse the received web service response.

The following sub-sections describe an example for calling a SOAP web service using the NSURLConnection class and parsing a web service response.

Building a SOAP Web Service Request and Calling a Web Service

An example below represents the NSURLConnection class usage for a SOAP Web Service call. The following example implements both NSURLConnectionDelegate and NSXMLParserDelegate classes, and delegate methods for implementing a web service call and web service response functionality.

Starting point of a SOAP web service execution is the execute method. In case of successful web service call, the class calls the connectionDidFinishLoading:(NSURLConnection *)connection method to notify that web service response is received and data can be parsed. In case of any error, the class calls the didFailWithError:error() method to notify that a web service call cannot be executed.

//======#pragma mark SOAP Web Service Specific Functionality //======

// starting point for a SOAP request -(void)execute{ // Creating a request object and sets its URL theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[SettingsManager getSOAPUrl]] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];

// Setting specific SOAP headers // For the SOAP content type - text/xml [theRequest addValue:@"text/xml; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

// Ensuring the HTTP operation type is POST [theRequest setHTTPMethod: @"POST"];

// Creating a SOAP request string that to be posted to backend NSString * SOAPBody=@""

Page 56 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

"" "" "" ""; soapBody=[soapBody stringByAppendingString:requestDO.userID]; soapBody=[soapBody stringByAppendingString: @"" "" "" ""

// Setting a SOAP envelope as request body [theRequest setHTTPBody:[SOAPBody dataUsingEncoding:NSUTF8StringEncoding]];

// Executing the non-SOAP specific logic [self makeReqest]; }

//======#pragma Common methods for NSURLConnection delegate Methods //======

-(void)makeReqest{ // If we want to use the SAP Logon ticket for authentication // we must enable the Cookies handling [theRequest setHTTPShouldHandleCookies:[SettingsManager getShouldUseSAPLogonTicket]];

// Show an activity indicator [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

// Create a connection object conn=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

//If connection could not be opened, return an error message if(!conn){ // Hide a network activity indicator [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

// Send an error to an application via delegate methods if ([delegate respondsToSelector:@selector(serviceProvider:didFailWithError:)]) { NSMutableDictionary* info = [NSMutableDictionary dictionaryWithObject:[theRequest URL] forKey:NSErrorFailingURLStringKey];

[info setObject:@"Could not open connection" forKey:NSLocalizedDescriptionKey]; NSError* error = [NSError errorWithDomain:@"SOAPServiceProvider" code:1 userInfo:info]; [delegate serviceProvider:self didFailWithError:error]; } } }

//======#pragma mark NSURLConnection delegate Methods //======

// delegate method that is called when connection receives the Basic authentication challenge from the backend // For more details on methods implementation, see the Authentication Handling section - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ NSInteger count = [challenge previousFailureCount];

if(count==0){ [self handleAuthenticationChallange:challenge]; } else {

Page 57 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

currentAuthenticationChallenge = challenge; [self showCredentialsPromt]; } }

// delegate method is called when the response code is received and data is ready to be loaded - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;

// getting the status code of a response int statusCode = [httpResponse statusCode];

// if the status code is not 200 or 500, the technical error occurs // and we must show an error to a user if( statusCode != 200 && statusCode != 500){ // returns an error to SOAPGetUserDetails delegate if([delegate respondsToSelector:@selector(serviceProvider:didFailWithError:)]){

//gets the current status code description from a property file NSMutableDictionary* info = [NSMutableDictionary dictionaryWithObject: [NSHTTPURLResponse localizedStringForStatusCode:statusCode] forKey:NSLocalizedDescriptionKey];

// returns an error to SOAPGetUserDetails delegate NSError* error = [NSError errorWithDomain:@"GetUserDetails" code:1 userInfo:info]; [delegate serviceProvider:self didFailWithError:error]; } [connection cancel]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } else { // if the status code is 200, a web service response can be loaded // if the status code is 500, a web service error message can be loaded // so we are accepting both cases and continue reading data [receivedData setLength:0]; } }

// delegate method is called when data is received - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // note that data can be received in several chunks //so it must be accumulated it global variable before it can be used [receivedData appendData:data]; }

// delegate method that is called when the data loading is successfully finished - (void)connectionDidFinishLoading:(NSURLConnection *)connection{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

// create a SOAP Parser object and parse the received data SOAPResponseParser * parser = [[[SOAPResponseParser alloc] init] autorelease];

// note that a class must implement the parser delegate methods [parser setDelegate:self]; [parser parseData:receivedData]; }

// delegate method that is called when an error occurred during the data loading - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; //returns error to SOAPServiceProvider delegate if([delegate respondsToSelector:@selector(serviceProvider:didFailWithError:)]){ NSLog([error localizedDescription]);

Page 58 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

[delegate serviceProvider:self didFailWithError:error]; } }

Parsing a SOAP Web Service Response

Instead of more common DOM parser, iPhone SDK provides developer with the NSXMLParser Event-Driven parser class. For this parser, a developer must implement parsing delegate that reacts on appearance of tags with particular name and performs related business logic. For example, when the tag with name A appears during parsing, stores the tag value in the application memory.

Typical SOAP response parser must define reaction on SOAP-ENV:Body tags elements as well as SOAP-ENV:Fault tag elements to cover both successful and unsuccessful web service calls.

For example, if the SOAP service call is successful, returns the following response:

John Doe

and error response returns the following (common to all web services):

SOAP-ENV:Server Authentication failed

A user must define reaction for the following tags:

Tag Name Description firstName Service specific tag that contains first name of a user. lastName Service specific tag that contains last name of a user. faultstring Common tag for all SOAP services that contains short description of an error message.

A code sample for parsing delegate implementation follows:

Page 59 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

//======#pragma mark Interface Methods //======

-(void)parseData:(NSData*)data{ // create a parser instance // and allocate it with data parser = [[NSXMLParser alloc]initWithData:data];

// set self as a parser delegate to handle parser events [parser setDelegate:self];

// start parsing a process [parser parse]; }

//======#pragma mark NSXMLParserDelegate Methods //======

// function called when the "elementName" tag is found - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{

// generates a selector (function reference) from elementName

// It doesn't work for iPhone SDK methods setShouldProcessNamespaces: setShouldReportNamespacePrefixes: // and setShouldResolveExternalEntities: // so firstly, remove the xml namespace ( "pns:" )from the tag name. NSString * selectorName = [elementName stringByReplacingOccurrencesOfString:@"pns:"withString:@""];

// and append ":" to have the selector name selectorName=[selector stringByAppendingString:@":"];

// get a function reference from the selector name. // If the function with such name is implemented // we will have a reference to the tag value handler in the tagSelector variable tagSelector = NSSelectorFromString(selector);

// The tag contents are accumulated inside the string buffer // so we must clean buffer when each tag is starting if (!stringBuffer) { [stringBuffer release]; stringBuffer = nil; } stringBuffer = [[NSMutableString alloc] initWithCapacity:50]; }

// The function is called when data found in xml - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ // append current string to tag value // tag value may come in several parts [stringBuffer appendString:string]; }

// The function is called when the end tag is found - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

// when the tag ends, we check whether we have a selector for this particular tag name implemented // and in case we have, we execute this selector to set the tag value

Page 60 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

if([self respondsToSelector:tagSelector]){ [self performSelector:tagSelector withObject:stringBuffer]; tagSelector=nil; [stringBuffer release]; stringBuffer = nil; } }

// The function is called when an error message occurs - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{ // thrown an exception here }

- (void)parserDidEndDocument:(NSXMLParser *)parser{ // all data object fields are now }

//======#pragma mark Property Setters //======

// storing tag values inside an internal object

-(void)firstName:(NSString*)string{ // store firstname tag value }

-(void)lastName:(NSString*)string{ // store lastname tag value }

-(void)faultstring:(NSString*)string{ // store error value returned from backend }

It is very easy to adjust code example above to handle the additional tag parsing. To react on the "myTag" tag, add the following method inside the class:

-(void)myTag:(NSString*)string{ // store myTag value }

For more information on parsing XML data, see the following links:

Resource Link iPhone Reference Library: XML Parsing http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ XMLParsing/Articles/UsingParser.html#//apple_ref/doc/uid/20002264 Mac OS X Reference Library: Event-Driven http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ XML Programming Guide for Cocoa XMLParsing/XMLParsing.html Mac OS X Reference Library: Using http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ Multiple Deligates for Parsing Web Service XMLParsing/Articles/UsingMultipleDelegates.html#//apple_ref/doc/uid/20002267 Response SOAP Protocol Definition http://www.w3.org/TR/soap/

Alternative Ways for Performing Web Service Call

As an alternative to the method described above (method of manual building web service request and parsing web service response), it is possible to use the third-party libraries or utilities that support Proxy Classes generation for calling

Page 61 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development web services. An example of such utility is wsdl2objc. This utility provides functionality for generation of the Objective-C (Cocoa) classes from a WSDL for calling SOAP web services.

For more information on wsdl2objc, see the following links:

Resource Link wsdl2objc project homepage http://code.google.com/p/wsdl2objc/ wsdl2objc usage instructions http://code.google.com/p/wsdl2objc/wiki/UsageInstructions

Third-party frameworks are available for managing the SOAP requests. For more information, see the following links:

Resource Link Third-Party Framework: gSOAP http://www.cs.fsu.edu/~engelen/soap.html Third-Party Framework: Apache Axis2 http://ws.apache.org/axis2/c/

Additional Information

For more information and examples on calling SOAP Web Services, see the following link:

Resource Link iPhone Programming Tutorial: Intro to SOAP Web Services http://icodeblog.com/2008/11/03/iphone-programming-tutorial-intro- to-soap-web-services/

Implementing a REST/JSON Web Service Call

REST is one of web service implementation protocols, that can be used for providing data via HTTP/HTTPS protocols. Protocol assumes that web service is called using the HTTP GET request, passing all request parameters in the service URL as url parameters. As the response, data in XML or JSON format can be returned. The current example demonstrates the JSON format usage.

Web Service Interface

A sample REST web service used in demo application provides the following interface:

Request The Http GET request to a web service URL by providing entered username as the url parameter:

?username=

Success Response In case of successful response, backend returns status code 200 and response in the following format:

{"UserDetails":{"firstName":"","lastName":""}}

Error Response In case of error, backend returns the HTTP status code 500 and response in the following format:

{"error":"User BOB does not exist"}

Following sub-sections describe an example for calling a REST web service using the NSURLConnection class and parsing the JSON web service response.

Page 62 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

Building the REST Web Service Request and Calling a Web Service

An example presenting the NSURLConnection class usage for the REST Web Service call is provided below. This example implements the NSURLConnectionDelegate class delegate methods for the web service call functionality implementation. When a web service response data is received, JSON Framework is used to parse the data.

Starting point of the REST web service execution is the execute method. Similar to the SOAP web service call example, in case of successful web service call, the class calls the didReceiveData:data method to notify that the web service is received and the data is parsed. In case of any errors, the class calls the didFailWithError:error method to notify that the web service call cannot be executed.

//======#pragma mark SOAP Web Service Specific Functionality //======

// starting point for a SOAP request -(void)execute{ // Create request URL by appending request parameter to URL NSString * url = [[SettingsManager getRESTUrl] stringByAppendingFormat:@"%@%@", @"?username=",username];

// Creates a Request object and sets its url theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];

// Specifies the GET as HTTP operation [theRequest setHTTPMethod: @"GET"];

// continues with REST non-specific operations [super makeReqest]; }

//======#pragma Common methods for NSURLConnection delegate Methods //======

-(void)makeReqest{ // if we want to use the SAP Logon ticket for the authentication, // we must enable Cookies handling [theRequest setHTTPShouldHandleCookies:[SettingsManager getShouldUseSAPLogonTicket]];

// show an activity indicator [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

// Creates a connection object conn=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

//if connection cannot be opened, returns an error message if(!conn){ // hide network activity indicator [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

// send error to application via delegate methods if ([delegate respondsToSelector:@selector(serviceProvider:didFailWithError:)]) { NSMutableDictionary* info = [NSMutableDictionary dictionaryWithObject:[theRequest URL] forKey:NSErrorFailingURLStringKey];

[info setObject:@"Could not open connection" forKey:NSLocalizedDescriptionKey]; NSError* error = [NSError errorWithDomain:@"SOAPServiceProvider" code:1 userInfo:info]; [delegate serviceProvider:self didFailWithError:error]; } }

Page 63 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

}

//======#pragma mark NSURLConnection delegate Methods //======

// delegate method that is called when connection receives the Basic authentication challenge from the backend // For more implementation details for this methods, see the Authentication Handling section - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ NSInteger count = [challenge previousFailureCount];

if(count==0){ [self handleAuthenticationChallange:challenge]; } else { currentAuthenticationChallenge = challenge; [self showCredentialsPromt]; } }

// deligate method is called when the response code is received and data is ready to be loaded - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;

// getting the status code of the response int statusCode = [httpResponse statusCode];

// if status code is not 200 or 500, then technical error occurrs // and we must show an error to a user if( statusCode != 200 && statusCode != 500){ // returns an error to the SOAPGetUserDetails delegate if([delegate respondsToSelector:@selector(serviceProvider:didFailWithError:)]){

//gets the current status code description from the property file NSMutableDictionary* info = [NSMutableDictionary dictionaryWithObject: [NSHTTPURLResponse localizedStringForStatusCode:statusCode] forKey:NSLocalizedDescriptionKey];

// returns an error to SOAPGetUserDetails delegate NSError* error = [NSError errorWithDomain:@"GetUserDetails" code:1 userInfo:info]; [delegate serviceProvider:self didFailWithError:error]; } [connection cancel]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } else { // if the status code is 200, a web service response can be loaded // if the status code is 500, a web service error message can be loaded // so we are accepting both cases and continue reading data [receivedData setLength:0]; } }

// delegate method called when the data is received - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // note that data may be received in several chunks // so it must be accumulated in global variable before it can be used [receivedData appendData:data]; }

//======#pragma mark NSURLConnection delegate Methods (REST specific for parsing response data) //======

Page 64 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

// delegate method that is called when the data loading is successfully finished - (void)connectionDidFinishLoading:(NSURLConnection *)connection{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

// recieved data is now available in 'receivedData' // implement data parsing functionality goes here ... [self doParseResponse:receivedData]; }

// delegate method that is called when error occurred during the data loading - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; //returns an error to SOAPServiceProvider delegate if([delegate respondsToSelector:@selector(serviceProvider:didFailWithError:)]){ NSLog([error localizedDescription]); [delegate serviceProvider:self didFailWithError:error]; } }

Parsing the REST Web Service Response

To parse the JSON response, the JSON Framework library is used that provides API for parsing JSON data using Objective C. An example of JSON Framework API usage follows:

//method is called when the data is received - (void)doParseResponse:(NSData*)data{ // Converting the received data to a string for parsing NSString * jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

// Creating a parser insitance and parsing data SBJsonParser *parser = [SBJsonParser new]; NSDictionary * rootDictionary = [parser objectWithString:jsonString];

// as the result of parsing, rootDictionary contains JSON objects converted to Obejectice C objects, // keeping hierarchy of objects the same

//if the root dictionary contains object for the "UserDetails" key //that means we have received the child dictionary with data

if([rootDictionary objectForKey:@"UserDetails"]!=nil){ //get the child dictionary NSDictionary * childDictionary=[rootDictionary objectForKey:@"UserDetails"];

// read response values and store them to variables for future use userFirstName = [childDictionary objectForKey:@"firstName"]; userLastName = [childDictionary objectForKey:@"lastName"]; } else { // if the dictionary doesn't contains object for the "UserDetails" key // we assume that we received the error response

// store the error message value for future use errorMessage = [rootDictionary objectForKey:@"error"]; }

[jsonString release]; [parser release]; }

Page 65 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

Additional Information

For more information on implementing the REST web service calls and parsing JSON data, see the following links:

Resource Link Dev Center: Creating RESTful http://developer.apple.com/safari/articles/creatingrestfulclients.html Web Service Clients in Cocoa and Cocoa Touch JSON Framework Home Page http://code.google.com/p/json-framework/ JSON format home page http://www.json.org/

Available Authentication Mechanisms

Several authentication mechanisms can be supported using iPhone SDK. Some of mechanisms, such as basic authentication and client certificate authentication are available out of box. Such mechanisms as SAML, Logon token, and other, must be implemented manually.

This section provides guidelines on how to use supported authentication mechanisms in iPhone applications, as well as presents requirements for using the SAP Logon ticket from the iPhone Application.

Supporting Basic Authentication

To support basic authentication, NSURLConnection delegate must implement -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge method.

Using this method, a developer has options in reacting to the basic authentication challenge from a server and provide a request to enter user credentials or provide user credentials from the application memory/cache.

Below is code snippet showing example for requesting user credentials from user on authentication challenge.

// delegate method inside class that is responsible for performing data call -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ NSInteger count = [challenge previousFailureCount];

if(count==0){ // Authentication is requested for the first time // try to provide user credentials stored in the application NSURLCredential* credential = [[NSURLCredential alloc]initWithUser:username password:password persistence:NSURLCredentialPersistenceNone];

[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; [credential release]; } else { // initially provided credentials are not valid // ask a user to provide the valid credentials [SecurityUtil showCredentialsRequestFormForAuthenticatonChallange:challenge]; } }

// delegate method inside the SecurityUtil class that reacts on button click inside the login form - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

switch (buttonIndex) { case CANCEL_BUTTON: // cancel the authentication request [[authenticationChallange sender] cancelAuthenticationChallenge:authenticationChallange]; break;

Page 66 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

case OK_BUTTON: // read user credentials from the form NSString * username=[(UITextField*)[alertView viewWithTag:UITextFieldTypeUsername]text]; NSString * password=[(UITextField*)[alertView viewWithTag:UITextFieldTypePassword]text]; if(username==nil || password==nil){ // if credentials are not valid, prompt to reenter the data [SecurityUtil showCredentialsRequestFormForAuthenticatonChallange:challenge]; } else { // provide credentials NSURLCredential* credential = [[NSURLCredential alloc]initWithUser:username password:password persistence:NSURLCredentialPersistenceNone];

[[authenticationChallange sender] useCredential:credential forAuthenticationChallenge:authenticationChallange]; [credential release]; } break; default: break; } }

Note that iPhone SDK provides information about number of unsuccessful authentication attempts. This information can be used for implementing retry operation or canceling a request.

As an alternative, user name and password can be send to a server using the Authorization header.

[theRequest addValue:[SecurityUtil encodeBase64Username:username andPassword:password] forHTTPHeaderField:@"Authorization"];

The Authorization header value is represented in the following format: "Basic :", were ":" part is additionally encoded using basic 64 format.

For more information on implementing basic authentication, see the following links:

Resource Link iPhone Reference Library: Using NSURLConnection http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ URLLoadingSystem/Tasks/UsingNSURLConnection.html "Authorization" header usage in HTTP 1.0 http://www.w3.org/Protocols/HTTP/1.0/spec.html#BasicAA

Supporting a Client Certificate Authentication iPhone Applications share a common keystore for authentication management. Standard iPhone SDK API is able to use the client certificate from the keystore transparently to user when request is made using the HTTPS protocol. From development point of view, calling a web service that is protected using the client certificate is implemented in the same way as calling an unprotected web service.

theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://mysecurewebserivceurl" cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];

...

// Execute a web service call

Page 67 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

[self makeReqest];

For a request to be successful, a user client certificate must be imported inside a device. This can be performed by creating Configuration Profile using iPhone Configuration Utility.

Please note that starting from iPhone OS 3.0 self-signed certificates are not supported. For a certificate to work, a valid root certificate must be available in iPhone Keychain

When using the client certificate developer has API for controlling certificate acceptance based on the host name. This can be used for accepting client certificate only from specific hosts, or for accepting untrusted client certificates in development environments.

The code snippet for implementing a client certificate acceptance is provided below:

@implementation NSURLRequest(NSHTTPURLRequest)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host { return YES; // or any logic required }

For detailed information and useful hints on client certificate related topics, see the following links:

Resource Link iPhone Reference Library: Keychain http://developer.apple.com/iphone/library/documentation/Security/Conceptual/ Services Programming Guide keychainServConcepts/01introduction/introduction.html iPhone Reference Library: Certificate, Key, http://developer.apple.com/iphone/library/documentation/Security/Conceptual/ and Trust Services Programming Guide CertKeyTrustProgGuide/01introduction/introduction.html iPhone Reference Library: Generic http://developer.apple.com/iphone/library/samplecode/GenericKeychain/index.html Keychain usage example Enterprise Deployment Guide http://www.apple.com/support/iphone/enterprise/

Supporting SAP Logon Ticket

The SAP Logon ticket is specific cookie that is received from the backend on successful authentication. This cookie can be used for accessing Services and Applications that have the SAP Logon Ticket login module configured into authentication stack, which potentially allow to have SSO between several web services or systems inside system landscape.

To use the SAP Logon ticket, the following must be implemented:

// the request is an instance of NSMutableURLRequest [theRequest setHTTPShouldHandleCookies:YES];

The code represented above configures the NSMutableURLRequest class instance to accept cookies returned by the backend. Returned cookies are automatically stored and provided when the next request to the host is made.

For more information see the following links:

Resource Link Mac OS X Reference Library: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/ NSMutableURLRequest Class Reference Classes/NSMutableURLRequest_Class/Reference/Reference.html#//apple_ref/occ/ instm/NSMutableURLRequest/setHTTPShouldHandleCookies: SAP Help for NetWeaver 7.0: Using Logon http://help.sap.com/saphelp_nw70/helpdata/EN/53/ Tickets for Single Sign-On 695b3ebd564644e10000000a114084/frameset.htm

Page 68 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development Existing Development Documentation and Tools

This section contains development materials that can contribute to an application quality and can be useful during development process for solving the common development issues.

Apple Standards and Guidelines

Before starting an iPhone application development, a developer must refer official Apple documentation for detailed information on development guidelines and existing design patterns.

Resource Link iPhone Reference Library: iPhone http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/ Application Programming Guide iPhoneOSProgrammingGuide/Introduction/Introduction.html iPhone Reference Library: iPhone http://developer.apple.com/iphone/library/documentation/Xcode/Conceptual/iphone_ Development Guide development iPhone Reference Library: iPhone http://developer.apple.com/iphone/library/documentation/UserExperience/Conceptual/ Human Interface Guidelines MobileHIG/Introduction/Introduction.html Mac OS X Reference Library: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ Development Design Patterns CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html Mac OS X Reference Library: Apple http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/ Coding Guidelines for Cocoa CodingGuidelines.html Enterprise Deployment Guide http://www.apple.com/support/iphone/enterprise/

Memory Management Recommendations

Memory Management is one of challenging iPhone development tasks. There are several official and third party recommendations available on this particular topic.

Resource Link Mac OS X Reference Library: Memory Management http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ Programming Guide for Cocoa MemoryMgmt/MemoryMgmt.html Adrian Kosmaczewski Blog: 10 Practical Tips to avoid http://kosmaczewski.net/2009/01/28/10-iphone-memory-management-tips/ memory leaks Memory Management on iPhone Cocoa http://memo.tv/memory_management_with_objective_c_cocoa_iphone Objective C Memory Management http://macdevelopertips.com/objective-c/objective-c-memory-management. html General Objective C Guide (including Memory http://cocoadevcentral.com/d/learn_objectivec/ Management) Compilation of various links for Memory Management http://www.mobileorchard.com/iphone-memory-management/ topic

Development Tools

Xcode

During the application development Apple Xcode is used as a primary development tool.

The Xcode IDE provides a large set of tools for iPhone development tasks. The Xcode includes a large set of useful features, such as Code highlighting and Auto-complete, Refactoring, Debugger, Leak Analyzer, Static Code analyzer, integration with code Management systems, and other that assist developer in the daily routine. Apple's development documentation is also included as a part of Xcode suite.

Page 69 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

For more information, see the following links:

Resource Link xCode Home Page http://developer.apple.com/TOOLS/xcode/ Apple Development Tools Overview http://developer.apple.com/tools/overview.html Performance Tools homepage http://developer.apple.com/iPhone/library/documentation/Performance/Conceptual/ PerformanceOverview/PerformanceTools/PerformanceTools.html

More details on the specific XCode Tools are presented in the sub-sections below.

Xcode 3.2: Static Analysis

Xcode 3.2 available starting from Mac OS X 10.6 introduces a new tool called static analysis. The tool analyzes the application source code and provides information and warnings about potential bugs in the code. Static analysis has ability to investigate code deeper than regular compiler by walking through all logical path in the code and noting down potential logic and memory management issues.

Page 70 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

For more information on Static Analysis tool, see the following link:

Resource Link Static Analysis in Xcode http://developer.apple.com/mac/library/featuredarticles/StaticAnalysis/index.html

Xcode: Apple Shark

Shark is the Xcode suite tool that provides support for application performance analysis and optimization. Shark has ability to provide system kernel, drivers, and applications. It profiles all system aspects to identify places where the running time is being spent while an application is working. It can produce profiles of hardware and software performance events such as cache misses, virtual memory activity, memory allocations, function calls, or instruction dependency stalls. In addition to showing where time is being spent, Shark provide information on how to improve application code. This information can be used to identify code that should be optimized.

Page 71 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

For more information on the Shark tool, see the following link:

Resource Link iPhone Reference Library: Shark User Guide http://developer.apple.com/iphone/library/documentation/DeveloperTools/ Conceptual/SharkUserGuide/Introduction/Introduction.html

Code Analyzing Tools

There are several official and third-party tools available for analyzing the existing xCode project automatically and locating potential issues, bugs, and memory leaks.

Quick overview for such tools is provided below.

Clang Static Analyzer

Clang Static Analyzer consists both of a source code analysis framework and a standalone tool that finds bugs in C and Objective-C programs. The standalone tool is invoked from the command-line, and is intended to run in a tandem with a build of a project or a code base.

For more information, see the following links:

Resource Link Clang Static Analyzer homepage http://clang-analyzer.llvm.org/ Clang usage samples http://stackoverflow.com/questions/961844/using-clang-static-analyzer-from- within-xcode

Page 72 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

Resource Link http://www.mobileorchard.com/bug-finding-with-clang-5-resources-to- get-you-started/

GUI is also available for running Clang Static Analyzer called AnalysisTool.

AnalysisTool

AnalysisTool is a Mac OS X application which provides GUI and CLI frontends to the LLVM/Clang static analyzer, a tool that finds bugs in C and Objective-C programs. AnalysisTool includes a custom version of the LLVM/Clang static analyzer. AnalysisTool's version of Clang includes additional analysis and features, which are not included in the official LLVM/Clang static analyzer distribution.

For more information, see the following link:

Resource Link Analysis Tool homepage http://www.karppinen.fi/analysistool/#gui

Code Coverage Tools

Due to Objective C flexibility and specifics, code coverage can not be performed only using the design-time resources. A developer must run an application and use all application features to check the complete code coverage. Yet, there are some techniques and tools available that can assist a developer in this process.

For more information on known techniques, see the following link:

Resource Link Code Coverage analyzing guidelines http://seriot.ch/blog.php?article=20080728

For more information on existing tools, see he sub-sections below.

CoverStory

Coverstory is a GUI tool for analyzing which lines of the code were executed when a user run the code. It shows the code coverage for all project files, but requires developer to run the application and walk through all available functionality.

Page 73 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

For more information, see the following link:

Resource Link CoverStory Project homepage http://code.google.com/p/coverstory/

GCOV test coverage utility

GCOV is a test coverage program. Use it in concert with GCC to analyze the programs, to help create more efficient, faster running code, and to discover untested parts of the program. GCOV can be used as a profiling tool to help discovering where the optimization efforts has the best affect on the code. GCOV can be used along with the other profiling tool, gprof, to assess which parts of the code use the greatest amount of computing time.

For more information, see the following link:

Resource Link GCOV Test Coverage Tool homepage http://gcc.gnu.org/onlinedocs/gcc/Gcov.html

Other Tools

This section presents information on other tools used for iPhone application development. iPhone Configuration Utility iPhone Configuration Utility provide assistance for working with iPhone and iPod inside Enterprise environment on Mac OS X and Windows. The utility provides support for creating, maintaining, encrypting, and pushing configuration profiles, tracking and installing provisioning profiles and authorized applications, and capturing device information including console logs.

Configuration profiles contain various configuration settings, including the following:

• Device security policies • VPN configuration information • Wi-Fi settings • APN settings

Page 74 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

• Exchange account settings • Mail settings • Certificates

For instructions on how to use iPhone Configuration Utility, see the iPhone and iPod touch Enterprise Deployment Guide:

Resource Link Enterprise Deployment Guide http://www.apple.com/support/iphone/enterprise/ iPhone Configuration Utility homepage http://support.apple.com/kb/DL851

Tips and Tricks

This section presents tips and tricks that can be useful during the iPhone applications development.

Controlling an Application Mode

There are situation when application must run on different environments, for example development environment, test environment, and production environment. For each environment, the own set of configuration parameters can be required. This section presents how to have different configuration parameters for each environment and to switch between them.

Assume we have 3 environments as mentioned above: development (DEV), testing (QA) and production (PROD). We want to have different web service URLs for each environment and switch between them.

To implement this, firstly, define the additional key inside the Info.plist file with the env name . This key will hold ID of the current environment. Add 3 more keys inside the Info.plist file for holding the web service URL of each environment. Name each key as wsURL and add environment key as a part of parameter key, for example: wsURL.DEV, wsURL.QA, wsURL.PROD

The Info.plist file contents follows:

... env DEV ... wsURL.DEV http://mydevelopmenthost/webserviceurl wsURL.QA http://qahost/webserviceurl wsURL.PROD http://productionhost/webserviceurl

Code snippet displaying a way of how an application can read the wsURL value based on the env key value follows:

+(NSString*)getUrl{ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

// Initialize a dictionary object if (infoDict==nil){ infoDict = [[NSBundle mainBundle] infoDictionary]; } // Get the specified environment for the application

Page 75 of 88 MicroApps Technical User Guide - Appendix - iPhone Enterprise MicroApp Development

NSString *env = [infoDict valueForKey:@"env"]; NSString *url = [infoDict valueForKey:[NSString stringWithFormat:@"%@.%@", key, env]];

// If the dictionary doesn't have a specified URL value, the default value is read from application preferences if (url==nil){ // Get the url configuration setting for the app specified in the root.plist if([defaults stringForKey:@"URL"]!=nil) { url = [defaults stringForKey:@"URL"]; } else { url = defaultWSUrl; } } return url; }

This technique can be used for managing as many parameters as required.

Page 76 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Using Federated User Management Appendix - Single Sign-On Using Federated User Management

Contents:

• Single-Sign-On Using Federated User Management

Single-Sign-On Using Federated User Management

With this single-sign-on (SSO) option, the MicroApp container that is usually hosted by third party vendor, as well as the back-end data servers on premise use a federated user management by having a central identity provider. In this section, this SSO option is described in details using Security Assertion Markup Language (SAML).

The following topics are described in this section:

• Overview • SAP NetWeaver SAML Support • Using SAML with Enterprise MicroApps • ° Implementing Single Sign-On ° Implementing the Log Out Functionality

Overview

Security Assertion Markup Language - SAML is an XML-based standard for exchanging authentication and authorization data between security domains, between an identity provider (a producer of assertions) and a service provider (a consumer of assertions). The most important problem that SAML is trying to solve is the web browser Single Sign-On (SSO) problem. SSO solutions are abundant at the intranet level, for example, using cookies, but extending these solutions beyond the intranet has been problematic and has led to the proliferation of the non-interoperable proprietary technologies. SAML has become the definitive standard underlying many web SSO solutions in the enterprise identity management problem space. For more information on SAML, see http://saml.xml.org/.

SAP NetWeaver SAML Support

NetWeaver 7.0 and 7.1 supports accepting SAML Browser/Artifact Profile SSO tickets from external SAML identity providers. There are following constraints on NetWeaver SAML support: Versions 1.0 and 1.1 of the SAML specification are supported. The AudienceRestrictionCondition condition element is accepted by AS Java, although it is not evaluated. Any other child elements of the Conditions element result in processing errors. Assertions must have exactly one AuthenticationStatement element. The authentication statement must have a NameIdentifierelement. If they are present, the AuthorizationDecisionStatement and AttributeStatement elements are ignored. Creating digital signatures for outgoing documents is not supported. Digital signatures present with incoming documents are not verified. For information on SAP NetWeaver SAML support, see http://help.sap.com/saphelp_nw04s/helpdata/en/02/60d04e7971354890ecbde886363d1d/frameset.htm

Using SAML with Enterprise MicroApps

Implementing Single Sign-On

For SAML specification, client authentication with SAML involves cycles of HTTP redirections between SAP NetWeaver and SAML authority. Such redirections are not easily available for JavaScript triggered AJAX calls to the backend data, hence for web application Enterprise MicroApps scenarios it is usable only where a HTML page is requested. Once client has authenticated and received the HTML page from NetWeaver, there is the SAP logon ticket stored in the client

Page 77 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Using Federated User Management browser that can be used for the backend data calls through JavaScript AJAX. With this constraint, the best use of SAML authentication is web application Enterprise MicroApps scenarios where Web Application is authenticated using SAML and JavaScript AJAX calls reuses the SAP logon ticket stored in the browser for the backend data access.

The following diagram outlines the process of the SAML authentication in the web application Enterprise MicroApp scenario where the Enterprise MicroApps container supports the SAML authentication. Google Apps/Sites container is used as an example for the desired Enterprise MicroApps container:

Step description:

1. At this moment client has not authenticated neither with Google Apps nor with SAP NetWeaver. The process starts when a client navigats to the Google Apps Sites page in the browser. • Request: The HTTP GET request for Google Apps/Sites page issued by the client browser. • Response: Google responds with a HTTP redirect command pointing user's browser to SAML identity provider. The redirect URL includes the encoded SAML authentication request with the encoded URL of the Google application that the user is trying to reach 2. Initiate authentication with an Identity Provider • Request: Follows redirect URL, client browser issues the HTTP GET request to Identity Provider with the SAML authentication request encoded in URL parameters. • Response: Identity Provider responds with the login form requesting user to enter the username and password (this step depends on the client authentication configured on Identity Provider). Methods for identifying the user by Identity Provider could be different, e.g. SSL client certificate or other) 3. Complete authentication with Identity Provider • Request: When a user fills in login form and clicks the 'Submit' button, HTTP POST is sent to Identity Provider. • Response: When Identity Provider verifies user credentials, it generates a SAML response that contains the authenticated user username. In accordance with the SAML 2.0 specification, this response is digitally signed with the Identity Provider's public and private DSA/RSA keys. The SAML authority provides a mechanism so that the browser can forward that information to Google's ACS. For example, it could embed the SAML response and destination URL in a form and provides a button that can be clicked by a user to submit the form to Google. The Identity Provider could also include JavaScript on the page that automatically submits the form to Google. Along

Page 78 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Using Federated User Management

with the page content, Identity Provider stores the logon cookie that allows recognizing the user automatically upon the following request. • Logon cookies: At this stage the client possesses an IdP logon cookie 4. Request the Google Apps/Sites page with the SAML authentication • Request: using the mechanism provided by Identity Provider, the client browser forwards signed SAML authorization response to Google • Response: Google verifies the SAML authentication response and signature, and responds with the Google logon cookie and the Apps/Sites page content. • Logon cookies: IdP, Google Apps 5. Request the Web Enterprise MicroApp HTML content • Request: By the Enterprise MicroApp reference loaded from Google Apps/Sites, client browser requests the HTML content from the SAP NetWeaver Application Server • Response: Since client hasn't yet authenticated to NetWeaver, the SAML logon module redirects user to Identity Provider in same way as in step (1) 6. Acquire the SAML token for NetWeaver • Request: Following the redirect response from NetWeaver, client browser issues HTTP GET to Identity Provider. HTTP GET headers contains the Identity Provider logon cookie. • Resonse: Identity Provider recognizes the user based on its logon cookie passed in the request and immediately generates the SAML assertion for SAP NetWeaver. The unique token is assigned to the SAML assertion and stored in Identity Provider. Client receives the HTTP redirect back to NetWeaver with the SAML assertion unique token encoded in the response URL parameters. 7. Load the Web Enterprise MicroApp content • Request: Following the redirect from Identity Provider, client again request Web Enterprise MicroApp content, this time with SAML assertion unique token in URL • Response: NetWeaver in background verifies assertion unique token with Identity Provider and responds with the SAP logon ticket and Web Enterprise MicroApp content • Logon cookies: IdP, Google Apps, SAP 8. AJAX data call • Request: On SAP NetWeaver, JavaScript generates request to WebService from the Web Enterprise MicroApp, transparently passing the SAP logon ticket along with the request • Response:The data call is authenticated, based on the logon ticket and data is returned to the JavaScript method for further processing

Implementing the Log Out Functionality

When using SAML authentication for the Enterprise MicroApp, the logon data is stored in client cookies. The following cookies are involved in the communication process:

• the SAML session cookie • the HTTP session cookie • the SAP logon ticket

The SAML session cookie is generated when user is successfully logged into the SAML provider. NW uses this cookie to verify the user identity. The cookie name depends on the SAML provider. For example, the Sun Access Manager cookie name is "iPlanetDirectoryPro".

The HTTP session cookie is generated when the client is logged in NW. The NW Application server creates the standard java session between the server and the client. The session contains information about the logged in user name. The cookie name is "JSESSIONID".

If the Enterprise MicroApp is configured to generate the SAP logon ticket, it is also generated when the user successfully logs into NW for the first time. The SAP logon ticket is used for SSO to make out different backed systems. The SAP logon Ticket cookie name is "MYSAPSSO2".

In order to successfully log out from the application using SAML authentication, all three cookies must be cleared. It can be done by navigating to the special log out page, which clears the cookies.

The HTTP session is cleared using JAVA API. The invocation of the HttpSession.invalidate() method, clears the current session. The HttpSession object is retrieved using the HttpServletRequest.getSession() method. The "iPlanetDirectoryPro" and "MYSAPSSO2" cookies are cleared by sending the empty cookies to the client. Besides the empty cookie value, the domain, path, and expiration date for the cookie must be set. An example of the JSP code for clearing the cookie follows:

Page 79 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Using Federated User Management

<% // Clear the cookie with the "name" name Cookie c = new Cookie("name",""); c.setMaxAge(0); c.setPath("/"); c.setDomain("domain.com"); response.addCookie(c); %>

An example of the JSP log out page follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% // Clear the SAP logon ticket - cookie "MYSAPSSO2" Cookie c = new Cookie("MYSAPSSO2",""); c.setMaxAge(0); c.setPath("/"); c.setDomain(request.getServerName().substring(request.getServerName().indexOf('.'))); response.addCookie(c); // Clear SAML session - cookie "iPlanetDirectoryPro" c = new Cookie("iPlanetDirectoryPro",""); c.setMaxAge(0); c.setPath("/"); c.setDomain(request.getServerName().substring(request.getServerName().indexOf('.'))); response.addCookie(c); // Clear current session request.getSession().invalidate(); %> Logout <% if (request.getRemoteUser() == null ) { %>

You have sucessfully logged out!

<% } else { %>

User <%= request.getRemoteUser() %> still logged in!

<% } %>

Page 80 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Using Signed Fetch Appendix - Single Sign-On Using Signed Fetch

Contents:

• SSO Using Signed Fetch

SSO Using Signed Fetch

Contents:

• Overview • Using OAuth Signed Fetch with Enterprise MicroApps • ° Implementing Single Sign-On ° Security Considerations

Overview

In order to establish an SSO between the MicroApp container server in could and the back-end data server on premises, the MicroApp container user must be validated and mapped to the valid back-end data server user. This section, using OpenSocial container, describes how the user can be validated using the OAuth standard called Signed Fetch and how the user mapping can be done by SAP NetWeaver's user management functionality.

Using OAuth Signed Fetch with Enterprise MicroApps

Implementing Single Sign-On

When the OpenSocial container makes a data service request, the OpenSocial user, who is making the request, must be validated using the identity provided by the OpenSocial container following OAuth standard, and the user must be mapped to corresponding NetWeaver user for further user authorization. Such request could be called Signed request or Signed fetch. Details for the OpenSocial container's Signed request/fetch can be found at the following links: http://wiki.opensocial.org/index.php?title=Gadgets.io_(v0.8)#Signed_authorization http://wiki.opensocial.org/index.php?title=Introduction_To_Signed_Requests http://wiki.opensocial.org/index.php?title=Validating_Signed_Requests

Sample code and step-by-step guidelines on how to implement and configure this SSO option can be found at SDN Wiki page.

Even though conceptually container signature could be used on each request to validate and map user, due to performance and technical circumstances reference implementation suggests two step process, where container signed request is used to acquire SSO ticket and then ticket used for authentication of subsequent web service calls.

The following diagram describes how the web services are called using the OAuth Signed Request authentication. Google Apps/Sites container is used as an example for the OpenSocial container:

Page 81 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Using Signed Fetch

The detailed process of calling web service using the OAuth signature follows:

1. Using the gadgets.io API, widget requests the logon ticket from the OAuth preauthentication servlet, requesting the OpenSocial container to vouch for the user identity. Vouching is specified by setting the AUTHORIZATION parameter to SIGNED as follows:

var params = {}; params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT; params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 1; params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;

gadgets.io.makeRequest(url, handleTicket, params);

2. The preauthentication call is picked up by the OpenSocial container, which vouches for the user identity by adding the OAuth attributes, including the currently logged user ID, and signes it. After it, the call is forwarded to the designated URL of the preauthentication servlet 3. The OAuth preauthentication servlet performs the following: For a user authentication and the SAP logon ticket generation, calls the JAAS stack. There are 3 modules chained in JAAS: a. Signature verification - using the OAuth library, first module verifies that all passed parameters are valid by checking signature attached to the request using predefined public certificate of the container. b. User mapping - a user ID returned from the container has to be mapped to a valid NetWeaver user. The OpenSocial specification assumes the usage of parameter opensocial_viewer_id, which is container internal GUID of the user viewing widget, however, specific containers might use additional parameters for less opaque identification of the user. For example, Google Sites provides option to transfer viewer email as parameter

Page 82 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Using Signed Fetch

opensocial_viewer_email - see more details on Googles help page topic Modify the Gadget to Access Private Data c. Ticket credentials generation - standard SAP module used to generate logon ticked for user found during user mapping step 4. When the JAAS stack execution is finished, the OAuth servlet checks the authentication status and generates the authentication status JSON message included to the response. Authentication results are returned to client gadget in JSON format: • If the authentication succeeds, the JSON message with the OK status, the SAP logon ticket and the principal in it is returned. The JSON message must resemble the following:

{ "Status" : "OK", "Principal" : "OAUTH", "Ticket" : "AjE14124basfAFSFSFSASFGApaiAbAAHZGVmYXVsdAEABkdPT0dMRQIAAzAwMAMAA 0NFMQQADDIwMDgxMDEzMTQzMwUABAAAAAgKAAZHT09HTEX%2FAQUwggEBgkqhkiG9w0BBwKggfMwg fACAQExCzAJBgUrDgMCGgUAMAsGCSqGSIbAFnASFASNADNFASnasdalAB0xDDAKBgNVBAMTA0NFMT ENMAsGA1UECxMESjJFsadadADFAgUrDgMCGUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAc BgkqhkiG9w0BCQUxDxcNMDgxMDEzMTQzMzA2WjAjBgkqhkiG9w0BCQQxFgQU3wQ1bzvy3N535bhVc YSZscTVr7gwCQYKoZIzjgEAwQvMC0CFF561RaH4ZbuY%2FckN68XN7E70BhOAhUA8qc9CGFLgpEcg v9mGlH3vBngLsA%3D" }

• If the authentication failed, JSON returns message with the FAILED status, including the principal, fault, and exception if such exists. The JSON message must resemble the following:

{ "Status" : "FAILED", "Exception" : "Cannot authenticate the user" }

The returned ticket is saved on the client side for later use in the SOAP web service call. The returned ticket resembles the following:

var response = gadgets.json.parse(m.text); if(response.Status == "OK") { TICKET.value = response.Ticket; }

5. As the gadget gets the valid SSO logon ticket, data web service can be called. The gadget issues the SOAP web service call by specifying the retrieved logon ticket in the HTTP header as a credential for the authentication as follows:

var requestXML = '' +' ' +' ' +' ' +' ' +'';

var params = {};

Page 83 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Using Signed Fetch

params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT; params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 1; params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST; params[gadgets.io.RequestParameters.POST_DATA] = requestXML; params[gadgets.io.RequestParameters.HEADERS] = { "Content-Type" : "text/xml; charset=utf-8", "Cookie" : "MYSAPSSO2=" + ticket }; gadgets.io.makeRequest(url, handleWS, params);

6. The call from the Google server is forwarded to the web service end point, where the logon ticket is read from the HTTP header and call is associated with the user context. 7. Logon ticked is verified and accepted by the JAAS stack configured on data service. The web service call is processed and returned to the user.

Security Considerations

In order to protect end-user data access, backend system must ensure that only approved OpenSocial microapplications are permitted to read user's data.

Google Apps Premier customers are given option to use "private gadgets" - OpenSocial MicroApps controlled by Google Apps administrators and with extended access to private data. Those gadgets are allowed to include container user email in signed fetch request by adding special parameter:

params['OAUTH_ADD_EMAIL'] = 'true'

As result, backend receives OAuth parameter opensocial_viewer_email. Non-private gadgets are not allowed to use opensocial_viewer_email, thus this parameter can be used for mapping securely, with confidence that user mapping and authentication will be performed only for widgets approved by Google Apps administrations. See more details on Googles help page topic Modify the Gadget to Access Private Data

Page 84 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Workaround Appendix - Single Sign-On Workaround

Contents:

• Single Sign-On Workaround

Single Sign-On Workaround

The followings are possible work-around solutions, if the MicroApp runtime environment does not support above mentioned SSO options:

• x.509 Client Certificate Authentication • ° Overview ° Prerequisites ° Configurations ° References • Master Logon Enterprise MicroApp Authentication • ° Overview ° Master Logon Enterprise MicroApp Approach ° Client Certificate Authentication x.509 Client Certificate Authentication

Overview

In addition to using SSL for encrypting connections, SSL and the X.509 client certificates can be used for authenticating the client or user access requests for NW applications. When using client certificates, authentication takes places transparently for the user with the underlying SSL protocol. Therefore, authentication with the client certificates can be used to integrate the NW into the SSO environment.

Users need to receive client certificates from a Certification Authority (CA) as a part of a public-key infrastructure (PKI). When using client certificates, users are authenticated at the communication protocol level using the SSL protocol. Therefore, configuring the SSL protocol is necessary for connections where the user authentication is required. When users access the NW applications with or without the intermediary gateway proxy server, NW enables the SSL protocol use or the user authentication with certificates.

Prerequisites

The following conditions must be met:

• Users possess the valid X.509 client certificate with public and private key issued by a trusted CA. • If the browser is used to access the NW application, user client certificates are imported into the client system web browsers. • The SAP NW AS Java is configured to support HTTPS connections and the SSL protocol.

To configure the not to display the client certificate selection window, proceed as follows:

1. In the Internet Explorer, select Tools > Internet Options > Security Tab > (Internet or Trusted Sites). 2. Click Custom Level. 3. In the Miscellaneous section, locate the Don't prompt client certificate selection when only one or none option. 4. Select the Enable ratio button.

Configurations

The SAP NW AS Java enables the user authentication with client certificates using the following configuration scenarios:

Page 85 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Workaround

Configuration scenarios information Item Reference Client certificates for users http://help.sap.com/saphelp_nwce71/helpdata/en/8a/8bc061dcf64638aa695f250ce7ca78/content. can be stored from the Identity htm Management functions of the SAP NW AS Java and access based on the user-certificate mapping can be authenticated in the UME data source of the SAP NW AS Java. Alternatively, rules for login http://help.sap.com/saphelp_nwce71/helpdata/en/43/e0aa7242260a29e10000000a11466f/content. with client certificates can be htm configured and user access can be authenticated directly from the certificate information. For this scenario, it is not required storing the certificate information for users. Configuration scenarios information Item Reference Client certificates for users http://help.sap.com/saphelp_nw70/helpdata/en/8a/8bc061dcf64638aa695f250ce7ca78/content.htm can be stored from the Identity Management functions of the SAP NW AS Java and access based on the user-certificate mapping can be authenticated in the UME data source of the SAP NW AS Java. Alternatively, rules for login http://help.sap.com/saphelp_nw70/helpdata/en/43/e0aa7242260a29e10000000a11466f/content. with client certificates can be htm configured and user access can be authenticated directly from the certificate information. For this scenario, it is not required storing the certificate information for users.

1. To deploy and configure the client certificate authentication, proceed as follows: 2. To protect web resources in NW using Basic authentication include in web.xml file following code:

CLIENT-CERT

3. In NW Administrator, select Configuration Management > Authentication. 4. Locate the deployed application and ensure the login module stack contains the ClientCertLoginModule module.

Page 86 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Workaround

The Login Modules section must resemble the following:

References

The following table describes related information required for configuring the NetWeaver web application:

NetWeaver web application related information Item Reference NW login modules http://help.sap.com/saphelp_nw70/helpdata/EN/20/f66e424925c253e10000000a1550b0/frameset. htm SSL http://en.wikipedia.org/wiki/Secure_Sockets_Layer NW SSL configuration http://help.sap.com/saphelp_nwce71/helpdata/en/f1/2de3be0382df45a398d3f9fb86a36a/frameset. htm

Master Logon Enterprise MicroApp Authentication

Overview

Master Logon Enterprise MicroApp approach covers the scenario when several Web Application as Enterprise MicroApps (for example type URL iGoogle gadgets), published inside same page, need to logon inside the same NW instance. While several Enterprise MicroApps can request the authentication, it must be sufficient for the user to enter credentials or perform the authentication only in single Enterprise MicroApp inside the page. Other must be automatically authenticated.

Master Logon Enterprise MicroApp Approach

The user has the special Enterprise MicroApp published inside the Enterprise MicroApp container page (for example Google Apps Sites container). The widget performs authentication and retrieves the SAP logon ticket. When the SAP logon ticket is retrieved, other widgets perform authentication using the SAP logon ticket.

Page 87 of 88 MicroApps Technical User Guide - Appendix - Single Sign-On Workaround

The following diagram describes how the widgets performs the authentication:

Client Certificate Authentication

Every Enterprise MicroApp published on server can be protected using the HTTPS protocol. The following table describes known issues and solutions using the client certificate for the Enterprise MicroApp authentication:

Known issues and solutions using the client certificate Issue Solution or comment A browser requests the client certificate for each widget that results It is possible to configure the browser not to display the client in several client certificate selection pop-ups being shown to user. certificate selection window if no or single certificate is available. The Request Client Certificate option is not configurable per web NW can be configured not to request the client certificate from application. the user when establishing the HTTPS connection, but it is applied for all applications on the NW instance.

To configure the Internet Explorer not to display the client certificate selection window, proceed as follows:

1. In the Internet Explorer, select Tools > Internet Options > Security Tab > (Internet or Trusted Sites). 2. Click Custom Level. 3. In the Miscellaneous section, locate the Don't prompt client certificate selection when only one or none option. 4. Select the Enable ratio button.

Page 88 of 88