Hide menu Last updated: Oct 20 2016
Area: Episerver Service API Applies to versions: 2 and higher Previous versions: Not applicable

Installation and configuration - Service API 2

This section describes how to install and configure EPiServer.ServiceApi as the integration service. 

Prerequisites

  • Microsoft .NET Framework 4.5.2. You can download the framework from Microsoft.

Installing NuGet packages

Install Episerver updates through the NuGet Package Manager in Visual Studio. See Installing Episerver updates for information.

Installing the Service API components

To set up the service layer and related components:

  1. Install the .NET Framework 4.5.2 Developer pack
  2. Open Visual Studio 2012 or higher (earlier versions do not support .NET 4.5.2).
  3. Open your Episerver-based solution (either the Commerce sample website or your actual solution), right-click the relevant project, select Properties, and set the target framework to .NET Framework 4.5.2 or higher.
  4. Use the menu option Tools > Nuget Package Manager > "Manage Nuget packages for Solution..." (or right-click on the solution References and select there).
  5. Click Settings to create a source pointing to the Episerver NuGet feed.
  6. Open the Online section and select the source you just created.
  7. Install EPiServer.ServiceApi or EPiServer.ServiceApi.Commerce if working with Commerce, and all dependencies (including both Episerver and third party packages) Episerver-based solution (either the Commerce sample website or your actual solution). Do not install EPiServer.ServiceApi or EPiServer.ServiceApi.Commerce on your Commerce Manager site.
  8. Use the menu option Tools > NuGet Package Manager > Package Manage Console, and run the command update-epidatabase.
  9. Running update-epidatabase or Automatic schema updates sets administrator permissions automatically but you should check that these have been set correctly. Otherwise, set account permissions for administrators to execute the Service API in the database (tblUserPermission). (If not, an HTTP 401 status is returned.)

  10. Open EPiServerFramework.config and make sure that <appData> has a <basePath> directory that points to a valid location for which IIS has write permissions.

    Note: Monitor this folder over time because there is no built-in cleanup.

  11. Open IIS, Edit Bindings, and assign a custom HTTPS binding (HTTPS is required for the integration service).
  12. Open the website to verify that it works.

Configuration modifications

When you install the NuGet package, some configuration settings are added to your web.config.

Token Timeout in Minutes

<appsettings>
	<add key="IntegrationTokenTimeout" value="60" />
</appsettings>

File Upload Maximum Size

To increase the maximum size that can be uploaded, change maxAllowedContentLength. Currently, the maximum file size that can be uploaded is 2 GB.

Note: maxAllowedContentLength is in bytes, while maxRequestLength is in kilobytes.

<system.webserver>
         <security>
		<requestFiltering>
			<requestLimits maxAllowedContentLength="524288000" />
		</requestFiltering>
	</security>
</system.webserver>
<system.web>
    <httpRuntime requestValidationMode="2.0" maxRequestLength="102400" />
</system.web>

Disable Attribute Routing

XMLService API automatically enables attributes routing.
If you already configured this, you can disable the Service API from automatically enabling attributes by adding an app setting.
For information, see Attribute Routing in ASP.NET Web API 2.

<appsettings>
	<add key="episerver:serviceapi:maphttpattributeroutes" value="false" />
</appsettings>

Disable SSL requirement for request

<appsettings>
	<add key="episerver:serviceapi:requiressl" value="false" />
</appsettings>

Change Membership Authentication

Change OAuthAuthorizationServerProvider in the container
using EPiServer.Reference.Commerce.Shared.Models.Identity;
using EPiServer.Security;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;

namespace EPiServer.ServiceApi.Sample.Helpers
{
    public class IdentityAuthorizationProvider : OAuthAuthorizationServerProvider
    {
        private readonly ApplicationSignInManager _signInManager;

        public IdentityAuthorizationProvider(ApplicationSignInManager signInManager)
        {
            _signInManager = signInManager;
        }

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();

            return Completed();
        }

        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var result = _signInManager.PasswordSignInAsync(context.UserName, context.Password, false, shouldLockout: true).GetAwaiter().GetResult();
            if (result == SignInStatus.Success)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                var principal = PrincipalInfo.CreatePrincipal(context.UserName);
                if (principal is GenericPrincipal)
                {
                    var generic = principal as GenericPrincipal;
                    identity.AddClaims(generic.Claims);
                }

                context.Validated(identity);
            }
            else
            {
                context.Rejected();
            }

            return Completed();
        }
        
        private static Task Completed()
        {
            var source = new TaskCompletionSource<object>();
            source.SetResult(null);
            return source.Task;
        }
    }
}


using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using EPiServer.ServiceLocation.Compatibility;
using Mediachase.Commerce;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Web;
using System.Web.Routing;

namespace EPiServer.Commerce.Sample.Business.Initialization
{
    [ModuleDependency(typeof(EPiServer.Commerce.Initialization.InitializationModule))]
    public class InitializationModule : IConfigurableModule
    {
        public void Initialize(InitializationEngine context)
        {
            
        }

        private static void MapRoutes(RouteCollection routes)
        {
        }

        public void Preload(string[] parameters)
        {
        }

        public void Uninitialize(InitializationEngine context)
        {
        }

        public void ConfigureContainer(ServiceConfigurationContext context)
        {
            context.Services.Configure(c => c.For<ICurrentMarket>().Singleton().Use<MarketStorage>());
            Func<IOwinContext> owinContextFunc = () => HttpContext.Current.GetOwinContext();
            context.Services.Configure(c => c.For<ApplicationSignInManager>().Use(() => owinContextFunc().Get<ApplicationSignInManager>()));
            context.Services.Configure(c => c.For<IOAuthAuthorizationServerProvider>().Singleton().Use<IdentityAuthorizationProvider>());
        }
    }
}

Startup configuration

The Service API makes uses of owin startup to handle some configuration. To use your own owin startup class, call the Service API startup method in your own class.

using MyWebApp;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(Startup))]

namespace MyWebApp
{
    ///
    /// Sets configuration for Owin functionality hosted in IIS.
    ///
    public class Startup
    {
        ///
        /// Configures the Owin application.
        ///
        ///The  to configure.
        public void Configuration(IAppBuilder app)
        {
            new EPiServer.ServiceApi.Startup().Configuration(app);
        }
    }
}
Authentication tokens

To use any EPiServer.ServiceApi RESTful method, you must obtain an "OAuth 2 Bearer Token" to send with the request.

Example: Request

using (var client = new HttpClient())
{
	client.BaseAddress = new Uri("https://mysite.com/");
	var fields = new Dictionary<string, string>
	{
		{ "grant_type", "password" },
		{ "username", username },
		{ "password", password }
	};
	var response = client.PostAsync("/episerverapi/token", new FormUrlEncodedContent(fields)).Result;
	if (response.StatusCode == HttpStatusCode.OK)
	{
		var content = response.Content.ReadAsStringAsync().Result;
		var token = JObject.Parse(content).GetValue("access_token");
	}
}			

POST /episerverapi/token HTTP/1.1 Host: mysite.com User-Agent: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36 Content-Type: application/x-www-form-urlencoded;charset=UTF-8 Content-Length: 29 Accept-Encoding: gzip grant_type=password username=test password=test

Example: Response

HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}
Sending request with tokens

Example

using (var client = new HttpClient())
{
	client.BaseAddress = new Uri("https://mysite.com/");
	client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());
	var content = new MultipartFormDataContent();
	var filestream = new FileStream(path, FileMode.Open);
	content.Add(new StreamContent(filestream), "file", "Catalog.zip");
	var response = client.PostAsync("/episerverapi/commerce/import/catalog", content).Result;
	if (response.StatusCode == HttpStatusCode.OK)
	{
		var returnString = response.Content.ReadAsStringAsync().Result;
		returnString = returnString.Replace("\"", "");
		Guid taskId = Guid.Empty;
		Guid.TryParse(returnString, out taskId);
	}
}
Troubleshooting

The following common issues may arise when you set up the Service API.

  • Make sure there is a valid certificate on the server from a trusted certificate authority for the site.
  • Make sure all Service API requests are HTTPS.
  • You receive an error when trying to send a file to an import method. The Service API stores uploaded files in the AppDataPath set in the episerverframework.config file. Make sure the specified folder has the proper security permissions for the application pool identity.
  • Make sure there is a proper owin startup. You can disable this if there is a key on the appsettings.
    <add key="owin:AutomaticAppStartup" value="false" />

Next steps

Comments

drewd
Post by drewd deleted, 2/16/2017 9:55:32 PM