<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom"><title type="text">Blog posts by Rejaie Johnson</title><link href="http://world.optimizely.com" /><updated>2017-12-18T05:40:45.0000000Z</updated><id>https://world.optimizely.com/blogs/rejaie-johnson/</id> <generator uri="http://world.optimizely.com" version="2.0">Optimizely World</generator> <entry><title>Web API + Service API + Cookie Auth Gotcha</title><link href="https://world.optimizely.com/blogs/rejaie-johnson/dates/2017/12/web-api-cookie-authentication-with-service-api-turned-on/" /><id>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;I ran into an interesting problem while on a past project this year - when we turned on Service API via OWIN, my authorized Web API endpoints were returning a 401. We were using cookie authentication for the Web API endpoints. This baffled me a bit until I peeled back the code for Service API.&lt;/p&gt;
&lt;p&gt;When one of the Service API&#39;s initialization modules executes, it bypasses the default host authentication by calling &lt;span&gt;&lt;span style=&quot;text-decoration: underline;&quot;&gt;SupportDefaultHostAuthentication&lt;/span&gt;&amp;nbsp;&lt;/span&gt;on the Global HTTP Configuration. This explains why my API endpoints weren&#39;t recognizing the logged in user&#39;s cookie. I came up with a workaround that ignored this call and used cookie authentication instead. See below - during this project, we were using Episerver 10.9.1, and Service API 3.0.1:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Add the following code to your OWIN startup. This code ultimately re-adds cookie auth to the Web API filter pipeline&lt;/p&gt;
&lt;pre class=&quot;language-html&quot;&gt;&lt;code&gt;GlobalConfiguration.Configuration.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;In your API controller, decorate your controller or action with the System.Web.Http&#39;s&amp;nbsp;&lt;span style=&quot;text-decoration: underline;&quot;&gt;Authorize&lt;/span&gt; Attribute&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After I made these changes, I was able to access my authorized Web API endpoints. As a quick note, if you do use cookie authentication for your Web API endpoints, you may want to send an antiforgery token to protect against XSRF attacks. In this project, I sent the antiforgery token as a header&amp;nbsp;and created a filter attribute that validated the token against the logged in user&#39;s cookie. In case anyone is interested, here was my setup:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;In my master layout, I included a global antiforgery token. I placed this right after the &amp;lt;body&amp;gt; tag, but you can place this anywhere.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;In my client side code, I sent the&amp;nbsp;antiforgery token as a header. I called the &lt;em&gt;__RequestVerificationToken&lt;/em&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;On the server side, I created an attribute called &lt;span style=&quot;text-decoration: underline;&quot;&gt;UserValidateAntiForgeryTokenAttribute&lt;/span&gt; that inherited from &lt;span style=&quot;text-decoration: underline;&quot;&gt;FilterAttribute&lt;/span&gt; and &lt;span style=&quot;text-decoration: underline;&quot;&gt;IAuthorizationFilter&lt;/span&gt;. In the ExecuteAuthorizationFilterAsync method, I grabbed the cookie and token values and validated them against each other.
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code&gt;public Task&amp;lt;HttpResponseMessage&amp;gt; ExecuteAuthorizationFilterAsync(HttpActionContext actionContext,
            CancellationToken cancellationToken, Func&amp;lt;Task&amp;lt;HttpResponseMessage&amp;gt;&amp;gt; continuation)
        {
            try
            {
                // get headers
                var headers = actionContext.Request.Headers;

                // get cookie value
                var cookieRvtValue = headers
                    .GetCookies()
                    .Select(c =&amp;gt; c[AntiForgeryConfig.CookieName])
                    .FirstOrDefault()
                    ?.Value;

                // get header value
                var headerRvtValue = headers.GetValues(&quot;__RequestVerificationToken&quot;).FirstOrDefault();

                // validate
                AntiForgery.Validate(cookieRvtValue, headerRvtValue);
            }
            catch
            {
                actionContext.Response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.Forbidden,
                    RequestMessage = actionContext.ControllerContext.Request
                };
                var source = new TaskCompletionSource&amp;lt;HttpResponseMessage&amp;gt;();
                source.SetResult(result);
                return source.Task;
            }
            return continuation();
        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Decorate your Web API controller action with the attribute&lt;/p&gt;
&lt;pre class=&quot;language-html&quot;&gt;&lt;code&gt;[UserValidateAntiForgeryToken]
[Authorize]
[HttpGet]
public string DoGetAction()
{
     // do something
     return string.empty;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Thanks for reading. Hope you find this helpful!&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</id><updated>2017-12-18T05:40:45.0000000Z</updated><summary type="html">Blog post</summary></entry> <entry><title>Securing Web API Endpoints with Owin + Oauth 2.0, Part II</title><link href="https://world.optimizely.com/blogs/rejaie-johnson/dates/2017/5/oauth-2-0--owin--web-api-part-ii/" /><id>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;To recap Part I of this series, I showed you how you can configure ASP.NET Identity and Owin/Oauth to authenticate/authorize your Web API endpoints. Now, let&#39;s say you don&#39;t want to maintain different sets of user name/password combinations in a separate data store. Instead, ideally, you would like to maintain this information in Azure Active Directory Domain Services. If this is you, you&#39;re in luck. Here&#39;s another step-by-step guide on how I configured Azure AD with&amp;nbsp;OWIN inside of Episerver. This set up assumes you are making server-server authentication calls. &lt;strong&gt;Disclaimer&lt;/strong&gt;&lt;span&gt;: I ran this POC on Episerver 10.8.0, so later versions should work with this configuration. Unfortunately, I&#39;m not sure if earlier versions will be compatible:&lt;/span&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;First, you will need to ensure Azure Active Directory is enabled in your subscription. Here&#39;s a &lt;a href=&quot;https://docs.microsoft.com/en-us/azure/active-directory-domain-services/active-directory-ds-getting-started-enableaadds&quot;&gt;link&lt;/a&gt; on how to do this.&lt;/li&gt;
&lt;li&gt;Next, you will need to create 2 apps, one for the Web API and one for the client. Here&#39;s a &lt;a href=&quot;https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-webapi-dotnet&quot;&gt;link&lt;/a&gt; on how to do this. You can follow steps 1 &amp;amp; 3 in the link (I will explain step 2 from the link next).&lt;/li&gt;
&lt;li&gt;Next, you will need to modify the Startup.cs file to use Azure Active Directory as the Authentication provider. Below you will find the code. Essentially, the Windows Active Directory options (&lt;span&gt;WindowsAzureActiveDirectoryBearerAuthenticationOptions&lt;/span&gt;)&amp;nbsp;will look at the credentials passed in from the request and will respond back with an Oauth 2.0 token, if the credentials are correct. The options class will need to be initialized with the Web API App&#39;s App URI ID (Audience) and Active Directory Name (Tenant).
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code&gt;public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            this.ConfigureAzureADAuth(app);
            WebApiConfig.Register(config);
            app.UseWebApi(config);
            app.UseServiceApiMembershipTokenAuthorization();
        }

        private void ConfigureAzureADAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Audience = ConfigurationManager.AppSettings[&quot;ida:Audience&quot;],
                    Tenant = ConfigurationManager.AppSettings[&quot;ida:Tenant&quot;],
                    AuthenticationType = &quot;OAuth2Bearer&quot;,
                }
            );

        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Next, create a console application project and give it a name. This console application will be used as our client to test the configuration.&lt;/li&gt;
&lt;li&gt;Next, ensure that the Microsoft.IdentityModel.Clients.ActiveDirectory NuGet package is installed.&lt;/li&gt;
&lt;li&gt;In the Main method, add the following code from below:&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;The code first creates an authentication context to your Active Directory Domain. The pattern for the URL used is https://login.windows.net/[Azure AD Domain Name].&lt;/li&gt;
&lt;li&gt;Next, you will need to enter the client app&#39;s Application ID and Key of the client application created in Step 2 as ClientCredentials. The key will be created under Keys in the client application.&lt;/li&gt;
&lt;li&gt;Next, you will need to acquire a token by sending the ClientCredentials to the Web API&#39;s App URI ID.&lt;/li&gt;
&lt;li&gt;After you send the ClientCredentials to the Web API&#39;s App URI ID, Azure AD will send you back an Oauth 2.0 Bearer token to use. Now, you can call the GetListOfNumbers endpoint with that token.
&lt;ul&gt;
&lt;li&gt;Code
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code&gt;class Program
    {
        static void Main(string[] args)
        {
            ADAzureAuthStuff();
        }

        static void ADAzureAuthStuff()
        {
            AuthenticationContext ac =
                new AuthenticationContext(&quot;https://login.windows.net/[Azure AD Domain Name goes here]&quot;); //Leaf node is Azure AD Domain name
            var clientCredentials = new ClientCredential(&quot;[Client Application ID goes here&quot;, &quot;[Client Application Key goes here]&quot;); //first parameter: Application ID, //Second Parameter is a key configured in the client application
            AuthenticationResult ar =
                ac.AcquireTokenAsync(&quot;[Web API App&#39;s App URI ID goes here]&quot;, //This parameter is the Web API App&#39;s Application ID URI
                                clientCredentials).Result;

            string result = string.Empty;
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue(&quot;Bearer&quot;, ar.AccessToken);
            HttpResponseMessage response =
                httpClient.GetAsync(&quot;http://alloy.dev.com/sample-api/getlistofnumbers&quot;).Result;

            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;
            }
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Screenshots of running code&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Token after targeting my Active Directory Domain and sending ClientCredentials to the Web API App&#39;s Applicaton ID URI&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;img src=&quot;/link/cc49b7757ef84af185438668d227261b.aspx&quot; /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Success Status&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;img src=&quot;/link/869ed2e8fff14c379e5ac40fadc24a0c.aspx&quot; /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Result&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;img src=&quot;/link/a7518a3419b643c99ef3708490e1cbd9.aspx&quot; /&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/ol&gt;
&lt;p&gt;There you have it - you now have two different ways on how to secure your Web API endpoints using OWIN, at least in a server-server authentication capacity. I&#39;m sure you are wondering - well, can I use OWIN to handle my authentication for content editors/admins&amp;nbsp;and customers? Of course you can! Here are some Episerver documentation&amp;nbsp;on how to do this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;/link/9e3ab295f8234005855614aa6a84561f.aspx&quot;&gt;Owin Authentication&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;/link/9fe1050fea0e468cbfa6009819921870.aspx&quot;&gt;Configure mixed-mode OWIN authentication&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;From there, you can definitely mix and match how you want users to authenticate to your Episerver&#39;s back-end, customer portal, and Web API endpoints.&lt;/p&gt;
&lt;p&gt;Happy coding!&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</id><updated>2017-05-31T17:52:13.0000000Z</updated><summary type="html">Blog post</summary></entry> <entry><title>Securing Web API Endpoints with Owin + Oauth 2.0, Part I</title><link href="https://world.optimizely.com/blogs/rejaie-johnson/dates/2017/5/oauth-2-0--owin--web-api/" /><id>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;In my &lt;a href=&quot;/link/04204d9d5d924fb1beb242938ce73d93.aspx&quot;&gt;last blog&lt;/a&gt;, I explained&amp;nbsp;how simple it is to expose a Web API endpoint inside of Episerver. Now, the next question is: How can you secure these endpoints? Here&#39;s a scenario - you&#39;ve created a scheduled job in Episerver to fetch data from an XML file, and you&#39;ve stored this data using &lt;a href=&quot;/link/7b5666f0001045ea937bc5d293e0d13f.aspx&quot;&gt;Dynamic Data Store&lt;/a&gt;. Now, you want your mobile and other supporting applications to consume this information by hitting Web API&amp;nbsp;endpoints inside of Episerver. Of course you don&#39;t want anyone/everyone hitting your endpoints, right? That could lead to a slew of issues. In pure Episerver fashion, it is pretty&amp;nbsp;straight-forward&amp;nbsp;and not as hard as you would think to secure Web API endpoints&amp;nbsp;using Oauth 2.0&amp;nbsp;through OWIN. In a nutshell, OWIN is a standard that essentially decouples IIS and the web application. In a 2-part series, I&#39;m going to walk you through how you can configure OWIN/Oauth inside of Episerver using ASP.NET Identity and Azure Active Directory as the authentication layer. First, below you will find the&amp;nbsp;steps I took to configure Owin/Oauth and ASP.NET Identity. &lt;strong&gt;Disclaimer&lt;/strong&gt;: I ran this POC on Episerver 10.8.0, so later versions should work with this configuration. Unfortunately, I&#39;m not sure if earlier versions will be compatible:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Install Owin-specific packages&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Install the Episerver ServiceAPI Nuget Package. This package will give you all of the goodies needed to use OWIN inside of Episerver (because it actually uses OWIN!).&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Configure Startup File&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Create a .cs code file under the root project folder called Startup.cs. This Startup class will be our entry point in configuring our authentication parameters for the&amp;nbsp;Web API endpoints.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Inside of the Startup.cs file, we need to make sure we lock down the Service API endpoints first. Let&#39;s add the following:&lt;/span&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code&gt;public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseServiceApiMembershipTokenAuthorization();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Above the namespace in the Startup.cs code file, add the following code. This line of code tells OWIN to use the Startup class as the entry point for configuration. Insert your namespace in the placeholder [NamespaceGoesHere]:&lt;/span&gt;&lt;span&gt;&lt;br /&gt;&lt;/span&gt;
&lt;pre class=&quot;language-html&quot;&gt;&lt;code&gt;[assembly: OwinStartup(typeof([NamespaceGoesHere].Startup))]&lt;/code&gt;&lt;/pre&gt;
&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Create ASP.NET Identity Backend&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Create another .cs code file under the root project folder named EpiApiAuthDbContext.cs. Inside of this code file, add the code from below. This is a simple Identity DB context that points to our custom authentication database. The string inside of the base constructor is the connection string to the database used to store this information. If the IdentityDbContext class does not resolve for you, please ensure that you have the Microsoft.AspNet.Identity.EntityFramework NuGet package installed. You can use Entity Framework Migrations to create the database, but in my case, I just cracked open SQL Server Management Studio and created the database. Also, don&#39;t forget to add your connection string in the web.config.&lt;/span&gt;
&lt;pre class=&quot;language-html&quot;&gt;&lt;code&gt;public class EpiApiAuthDbContext : IdentityDbContext
    {
        public EpiApiAuthDbContext()
            : base(&quot;EpiApiAuthContext&quot;)
        {
        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Create another .cs code file under the root project folder&amp;nbsp;named EpiApiAuthRepository.cs. Add the code from below. This repository class will be used to create and find users. In a later step, we will build an action that will create our dummy user to authenticate to the Web API (very similar pattern that&#39;s used to set up the admin account for DXC environments). For a full-fledge solution, you can build a UI for users (or admins) to create their username/password combination(s).&lt;/span&gt;
&lt;pre class=&quot;language-html&quot;&gt;&lt;code&gt;public class EpiApiAuthRepository : IDisposable
    {
        private EpiApiAuthDbContext _context;

        private UserManager&amp;lt;IdentityUser&amp;gt; _usrMgr;

        public EpiApiAuthRepository()
        {
            _context = new EpiApiAuthDbContext();
            _usrMgr = new UserManager&amp;lt;IdentityUser&amp;gt;(new UserStore&amp;lt;IdentityUser&amp;gt;(_context));
        }

        public async Task&amp;lt;IdentityResult&amp;gt; CreateUserAsync(UserModel userModel)
        {
            IdentityUser user = new IdentityUser();
            user.UserName = userModel.UserName;

            var createResult = await _usrMgr.CreateAsync(user, userModel.Password);

            return createResult;
        }

        public async Task&amp;lt;IdentityUser&amp;gt; GetUserAsync(string username, string password)
        {
            IdentityUser usr = await _usrMgr.FindAsync(username, password);
            return usr;
        }


        public void Dispose()
        {
            _context.Dispose();
            _usrMgr.Dispose();

        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Create Oauth Authorization Provider Class&lt;/span&gt;&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Create another .cs code file under the root folder named SimpleAuthorizationServerProvider.cs. This class inherits from OAuthAuthorizationServerProvider and overrides two methods: ValidateClientAuthentication and GrantResourceOwnerCredentials.&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;&lt;span style=&quot;text-decoration: underline;&quot;&gt;ValidateClientAuthentication&lt;/span&gt;&amp;nbsp; - this method is used to validate the &quot;client_id&quot; parameter. Here, we will just call the &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/dn385502(v=vs.113).aspx&quot;&gt;Validate&lt;/a&gt; method from the context since we&#39;re authenticating with the username/password combo.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;&lt;span style=&quot;text-decoration: underline;&quot;&gt;GrantResourceOwnerCredentials&lt;/span&gt; - This method will contain logic to authenticate the incoming request&#39;s username/password combo via the GetUser method in our Repository class. If the user is found, we will validate the request with the user&#39;s ASP.NET Identity. If not found, we will set an error.&lt;/span&gt;
&lt;pre class=&quot;language-html&quot;&gt;&lt;code&gt;public class SimpleAuthorizationProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add(&quot;Access-Control-Allow-Origin&quot;, new[] { &quot;*&quot; });

            using (EpiApiAuthRepository authRepository = new EpiApiAuthRepository())
            {
                IdentityUser user = await authRepository.GetUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError(&quot;invalid_grant&quot;, &quot;The user name or password is incorrect.&quot;);
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(&quot;sub&quot;, context.UserName));
            identity.AddClaim(new Claim(&quot;role&quot;, &quot;user&quot;));

            context.Validated(identity);

        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Complete Startup code&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Add the following code from below to complete the startup file:&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;First, we will set up our Oauth Authorization by specifying a Token endpoint, how long the token will stay active, allow insecure requests (TRUE should only be used&amp;nbsp;for development purposes only), and a provider that will handle the authorization of the incoming requests. &lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Next, we will register our Web API endpoints. If you&#39;ve registered your Web API endpoints, in the Global.asax.cs file, please remove that registration&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Also, we will tell the Startup to use this config for Web API.&lt;/span&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code&gt;public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            this.ConfigureOAuth(app);
            WebApiConfig.Register(config);
            app.UseWebApi(config);
            app.UseServiceApiMembershipTokenAuthorization();
        }

        private void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString(&quot;/token&quot;),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationProvider()
            };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Create Custom Authorize Attribute&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Add a .cs file under the root project folder called CustomAuthorizeAttribute. Add in the code from below. You will need to create a custom authorize attribute to secure the Web API endpoints. When I tried using the out-of-the-box Authorize attribute, Episerver constantly redirected me to the Login page. This was due to the fact that Episerver is still set to use Forms Authentication, which is what we want ultimately. The implementation below will bypass this and let the Oauth server authenticate the user. &lt;/span&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;NOTE&lt;/span&gt;&lt;span&gt;: I&#39;ve set the response to 403 instead of 401 if the user is not authorized. This is because if I set the response code to 401, the response will be redirected to log in Episerver log in page, which is not our desired outcome.&lt;/span&gt;
&lt;pre class=&quot;language-html&quot;&gt;&lt;code&gt;public class CustomAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (HttpContext.Current.User == null || HttpContext.Current.User.Identity == null)
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError) { ReasonPhrase = &quot;User not is authenticated.&quot; };
            }
            else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Create Web API Endpoints&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;Create your Web API endpoints inside of the Episerver project. You can refer to my &lt;a href=&quot;/link/04204d9d5d924fb1beb242938ce73d93.aspx&quot;&gt;previous blog&lt;/a&gt; on how to create your endpoints. For this example, I will have a Web API Controller called SampleApiController with 2 endpoints:&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;&lt;span style=&quot;text-decoration: underline;&quot;&gt;GetListOfNumbers&lt;/span&gt; - this endpoint will return a list of numbers&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;&lt;span style=&quot;text-decoration: underline;&quot;&gt;AddApiCredentials&lt;/span&gt; - this endpoint will create our dummy account to use to authenticate to our Oauth Provider. Of course, the credentials used need to pass any/all&amp;nbsp;security measures created by your team/client/company.&lt;/span&gt;&lt;span&gt;&lt;br /&gt;&lt;/span&gt;
&lt;pre class=&quot;language-csharp&quot;&gt;&lt;code&gt;public class SampleApiController : ApiController
    {
        [CustomAuthorize]
        [HttpGet]
        [ActionName(&quot;GetListOfNumbers&quot;)]
        public IHttpActionResult GetListOfNumbers()
        {
            return Ok(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9 });
        }

        [HttpPost]
        [ActionName(&quot;AddApiCredentials&quot;)]
        public async Task&amp;lt;IHttpActionResult&amp;gt; AddApiCredentialsAsync()
        {
            var adminUser = new UserModel()
            {
                UserName = &quot;epiadmin&quot;,
                Password = &quot;123456abcdef&quot;
            };

            using(var repo = new EpiApiAuthRepository())
            {
                await repo.CreateUserAsync(adminUser);
            }

            return Ok();
        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Let&#39;s start testing!!&lt;/span&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;For testing, I used Fiddler to make my GET/POST calls. However, you can use whatever you tool to test the configuration. First, you will need to create the dummy account to test. Make a POST call to the AddApiCredentials endpoint. This endpoint is very similar to the aspx page used to create an admin account for your Episerver site if deploying to a DXC environment for the first time.&lt;/span&gt; &lt;br /&gt;&lt;br /&gt; &lt;strong&gt;AddApiCredentials Post Call&lt;/strong&gt; &lt;br /&gt;&lt;br /&gt; &lt;span&gt;&lt;img src=&quot;/link/e5ed8e2cedf14506a3fd9d16140c912f.aspx&quot; /&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;AddApiCredentials&amp;nbsp;Response&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt; &lt;span&gt;&lt;img src=&quot;/link/075616ebb4f94f20b7a1ad401b3cca37.aspx&quot; /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Next, make a POST call to the token endpoint, sending the user name/password combination. The response should give you a response back with an access token and when it expires. In your client application, you can store this token somewhere.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Token&amp;nbsp;POST Call&lt;/strong&gt; &lt;br /&gt;&lt;br /&gt; &lt;span&gt;&lt;img src=&quot;/link/fc36dc385c484ed4b7e6c577120b5f03.aspx&quot; /&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Token&amp;nbsp;Response&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;img src=&quot;/link/23f09b23e43245b389bdb5c66161f0bb.aspx&quot; /&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Next, make a GET call to the GetListOfNumbers endpoint. Make sure that you send the access token as a Bearer token on the Authorization header. The response should give you back an array of numbers!&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;GetListOfNumbers GET Call&lt;/strong&gt; &lt;br /&gt;&lt;br /&gt;&lt;img src=&quot;/link/e7fde171619041b18fcfe6b9d8f2903e.aspx&quot; /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;GetListOfNumbers&amp;nbsp;Response&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt; &lt;span&gt;&lt;img src=&quot;/link/cb842b7d929f49e5a35457d02541cc2d.aspx&quot; /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span&gt;Next, delete the first four characters in the access token, and make the GET call to the GetListOfNumbers endpoint again. The response should give you a 500 or 403 since the access token is incorrect.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt; &lt;strong&gt;GetListOfNumbers Incorrect Token GET Call&lt;/strong&gt; &lt;br /&gt;&lt;br /&gt; &lt;span&gt;&lt;img src=&quot;/link/777005f72ee4439c92d9b0e010f21a05.aspx&quot; /&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;GetListOfNumbers Incorrect Token Response&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt; &lt;span&gt;&lt;img src=&quot;/link/0536b19b14d94e94b0a8df64b59eaced.aspx&quot; /&gt;&lt;br /&gt;&lt;br /&gt;&lt;img src=&quot;/link/698a7b0fc5ff409a86cdfb6244c34645.aspx&quot; /&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In Part II, I will discuss how to configure Azure Active Directory instead of ASP.NET Identity to grab an Oauth token to secure your Web API endpoints. Happy Coding!&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</id><updated>2017-05-31T17:52:06.0000000Z</updated><summary type="html">Blog post</summary></entry> <entry><title>Episerver CMS + Web API</title><link href="https://world.optimizely.com/blogs/rejaie-johnson/dates/2017/5/episerver-cms--web-api/" /><id>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;During my last Episerver project, I needed to stand up a Web API endpoint to grab data from an external source. Sounds easy enough, right? Actually, it is in Episerver. One of Episerver&amp;rsquo;s greatest strengths is the code base works really well with existing ASP.NET features like Web API. In the scenario above, you can easily wire up a Web API Controller just like you would in any MVC web application. Here are the steps I followed to set up a very simple Web API controller in Episerver:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Open your Episerver solution in Visual Studio&lt;/li&gt;
&lt;li&gt;Create an API controller named DummyApiController under the Controllers folder. From here, add an action to do something simple, such as returning the number 5.
&lt;p&gt;&lt;img src=&quot;/link/d4e1a64e3f18437c838afcf741ec7d95.aspx&quot; width=&quot;226&quot; alt=&quot;Image Step2-1.png&quot; height=&quot;110&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/link/ff527e02f3204989b8143c6edf3e65a6.aspx&quot; width=&quot;436&quot; alt=&quot;Image Step2-2.png&quot; height=&quot;157&quot; /&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;Create a code file named WebApiConfig.cs. This fill will contain a method called Register. This method will register the route to our custom API.
&lt;p&gt;&lt;img src=&quot;/link/1c136a8a381f45e0b151f2024e171954.aspx&quot; width=&quot;345&quot; alt=&quot;Image Step3-1.png&quot; height=&quot;126&quot; /&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;Add code to register your route with the application in the WebApiConfig.cs file.&lt;img src=&quot;/link/da41895a52c444018ba3483049c1d462.aspx&quot; width=&quot;681&quot; alt=&quot;Image Step4-1.png&quot; height=&quot;97&quot; /&gt;&lt;/li&gt;
&lt;li&gt;Next, call the register method in the Application_Start method. You can find this method in the global.asax.cs file&lt;img src=&quot;/link/02430b56729a434ea7a4a592c0d757c0.aspx&quot; width=&quot;681&quot; alt=&quot;Image Step5-1.png&quot; height=&quot;102&quot; /&gt;&lt;/li&gt;
&lt;li&gt;Fire up your app, and navigate to your API endpoint (http://host/app-api/getdummynumber). The request will return the number 5!&lt;img src=&quot;/link/e1da05fa6d5b49538ab74d2916112d45.aspx&quot; width=&quot;681&quot; alt=&quot;Image Step6-1.png&quot; height=&quot;148&quot; /&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;That&amp;rsquo;s it. Very, very simple. However, in this case, you will need to do a lot more in terms of security and data input validation. Hope this is helpful to you.&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</id><updated>2017-05-10T22:29:09.1630000Z</updated><summary type="html">Blog post</summary></entry></feed>