11/5/16

HTTP verb used is not allowed

When writing RESTful APIs, we often used the HTTP verbs to control our operations.


Http Verb
Description
GET
Reads information
POST
Create a record
PUT
Update a record
DELETE
Delete a record

Our MVC APIs usually are set with attributes to indicate the verb as well.


During the development process, we test our APIs with IIS Express, so there is no unexpected behavior. When deploying to our test and production environments, the web server settings may be set to only allow the most common verbs like GET, POST and OPTIONS.  If this is the case when we deploy our API, we may come across this error when testing out the PUT or DELETE operations:


405 - HTTP verb used to access this page is not allowed


A quick way to control that from our applications is to set the allow verb configuration in our web.config file. This overrides the IIS settings for our application.  We can do this by setting the following web server configuration.


<system.webServer>  

    <security>
      <requestFiltering>      
          <verbs allowUnlisted="false">
            <add verb="GET" allowed="true" />
            <add verb="OPTION" allowed="true" />
            <add verb="POST" allowed="true" />
            <add verb="DELETE" allowed="false" />
            <add verb="PUT" allowed="true" />          </verbs>              
      </requestFiltering>
     </security>   

    <modules>
      <remove name="WebDAVModule" />
    </modules>

    <handlers>
      <remove name="WebDAV" />
    </handlers>

  </system.webServer>



The settings above indicate that we want to allow GET,POST, OPTION and PUT, and DELETE should not be allowed.  We also need to remove a WebDAV module and handler that can raise this error as they intercept some of the less common verb like PUT and DELETE.

The advantage of doing the changes on the web.config over configuring IIS is that as the application is deployed on any other server/environment; no one has to remember to update that setting on IIS.

Hope that helps.


Originally published by ozkary.com

10/15/16

App Service Authentication with Azure AD

 When building SaaS solution, one of the most common cross cutting concerns is the authentication of users. For some solutions, the security implementation is handled by the application itself. In this article, we explore the use of Azure Active Directory (AAD) to provide the security services for our apps.

The application we are building is a Node.js backend API with an AngularJS front end. To follow along, create a web app on Azure and download the initial codebase by running the following command using the command window:

Clone the repo from Github. This creates a new folder (nodejs-azure-ad) and downloads the code.


git clone https://github.com/ozkary/nodejs-azure-ad.git


Update all the npm packages by typing (from the newly created folder nodejs-azure-ad)


npm init


This should update all the packages that are listed as dependencies in our package.json file. Now that we have the code, we can run it on its current state. From the command line and in our working directory, type the following:


node server


A NodeJs app should start showing the server location and some instructions on how to load the client user interface on the browser. Once the client application is loaded, the application looks like:

App services Azure AD Authentication


At this point, the app is showing us that the content is secured, and we need to login to the system. The AngulaJS code uses a service and controller to make an API call to the server to fetch the current user context (see section Client App Code). However, there is currently no integration with any identity provider that can allow us to authenticate the user, so there is no user context, and the application shows us the message to login.

  To get our application to work under the Azure AD authentication process, we can deploy the app to Azure and then we can enable the authentication. Let’s start by deploying our app first.

Deploy to Azure Using Local Git

To deploy the application on Azure, we first need to set the deployment options on our app. Login to Azure and follow these steps:

  • Select your web app from the app services view

  • From the App Deployment options select Deployment Options and select Local Git Repository which allows us to push changes from or local repo to Azure

  • From the App Deployment options now select Deployment credentials, set a username and password. This is needed when we are ready to deploy the code to Azure

Azure Deployment Settings

The last step is to get the Git Clone url from the Overview section. This is the url that we need to be able to create a remote Git repo and push our changes to Azure. Click on the Overview option, and find both the Git deployment username and clone url.

We have now created our deployment profile with Azure using a local Git repo, and we are ready to deploy.

Deploy to Azure

To deploy our app to Azure, let’s go to the directory where our code is located using the command line. When using Visual Studio Code, we can use the integrated terminal option from the view menu. On the terminal, we can type the following commands: (replace azure-clone-url with your Azure Git clone url)


git remote add azuread  azure-clone-url
git push azuread master


The first command adds a remote repo with the name of azuread that points to the repo on Azure defined by the clone url. The second command pushes our code to the remote repo to update our Azure app.  When pushing the code, we should see a prompt asking for the username and passwordThis is the information we created under the deployment credential configuration area, not your Azure login.

After entering our credentials, we should see information about the publishing process to Azure. Once this is complete, we can go back to the Azure app deployment -> Deployment options, and we should see that our initial deployment is successful. This is a confirmation that the app is deployed to Azure.

We can now run the app from Azure using the App url (overview blade on Azure -> Url).  We should see that the app is running and indicating us to login. We still have no authentication enable on our app, so the app continues to load the same as it did when running locally.  We now need to enable AD authentication on our app.

Enable Azure AD Authentication

Let’s get back to Azure and select our web app. Click on Select Settings -> Authentication / Authorization  and click on On for the App Service Authentication option. This enables additional options for which we need to select Log in with Azure Active Directory for the action to take and configure AD with the Express option to build an Active Directory (AD) protected app.

*Note: The Login with Azure AD when the request is not authenticated option forces a redirect and does not allow the option to provide anonymous access to any of the app content.

The express option is a quick way to create an app registration with AD authentication. It adds the basic settings to create the app profile under the Azure Active Directory configuration settings. It also configures the app to allow access to all the users under the current AD.  Yes, these are the login profiles.

Azure AD App Configuration


Testing our AD Enabled App

We can try to load our app again from the browser, and we should see a much different behavior. To login, use your Azure credentials.

*Note: If you are already logged in to Azure with the same browser, a redirect takes place, but no login is required as the identity provider already knows about your current session. 

To test the integration, we should open a new browser on private or incognito mode, depending on the browser. This does not load any current state or cookies that may affect our validation.  Take a few seconds to reload the app and come back.

Yes, the app is now redirecting to an identity provider. For us to see our app, we are now required to enter our AD username and password. This is not the credentials that we created for deployment. This is the credentials that we use to login to our azure portal. To understand what users are available on Azure AD, from the Azure main menu select Azure Active Directory -> Users and groups -> All users.

Azure AD Users


Authenticated Results

App Service Azure AD Authenticated App


Now that the app is running with AD authentication and after a successful login, we should see that our app now shows a welcome message.  We are able to know that the user is authenticated because our client code makes an API call to retrieve the user context information. If the context exists, the client code sets the identity object which is used by the HTML view to render the elements based on whether the user is authenticated or not.

Client App Code

The client code is implemented using AngularJS. The core of the app is written on the auth service, app controller and view.

Auth Service (source: app/app.js)


//source app/app.js

//simple validation of the user context
//calling api/user
function isAuth() {
    var deferred = $q.defer();
    var url = 'api/user';

    $http.get(url).then(function (res) {
        var user = res.data['session'];

        deferred.resolve(user);
    }, function (err) {
        deferred.reject(err);
    })

    return deferred.promise;
}


The service which makes the API calls to retrieve the context from the server.

Controller (source: app/app.js)


// main controller to check the user auth state
function ctrlApp($auth) {
    var ctrl = this;
    ctrl.identity = null;

    function loadContext() {
        //get the user context
        $auth.isAuth().then(function (res) {
            ctrl.identity = res;
        }, function (err) {
            ctrl.err = err;
        });
    }
    loadContext();
}


The controller uses the $auth service to retrieve the user context and sets the controller identity member.

HTML View (source: app/views/about.html)


<div id="secured" ng-if="ctrl.identity">
    <h1>Welcome {{ctrl.identity.firstname}}</h1>
    <i ng-if="!ctrl.user" class="fa fa-lock fa-5x"></i><br>
    <div class="lead" ng-if="ctrl.user">       
        <div class="container">
            <h2>My Profile</h2>
            <ul class="list-group text-left">
                <li class="list-group-item"><b>eMail:</b> {{ctrl.user.username}}</li>
                <li class="list-group-item"><b>FirstName:</b> {{ctrl.user.firstname}}</li>
                <li class="list-group-item"><b>Last Name:</b> {{ctrl.user.lastname}}</li>
            </ul>
        </div>
    </div>
</div>


The view uses the identity member to control what is displayed to the user.

Server Side Code

The server side code is implemented using Node.js. Our server app defines client (app/) and server (api/) routes.

APIs (source: modules/routes.js)


// source modules/routes.js
//secured routes – get user context
var user = null;
app.get('/api/user', profile)

//validate that the user profile is set on the authSession cookie
function profile(req, resp) {

    var authSession = req.cookies['AppServiceAuthSession'];
    if (authSession != null) {
        user = authSession;
    }
    resp.json({ session: user });
}              
  

The routes.js module defines the routes. For the user context validation, the code just looks for the AppServiceAuthSession cookies which is a secured and HTTP only cookie. This means that it is not accessible on the client side via JavaScript.

Both the server and client code are only aware of the security context of the user, but there is not enough information to know about the user’s claims. For this, we need to get more detail information about the user by doing an integration using OAuth and authentication tokens. This however needs to be covered in another article.



Summary
In this article, we are able to see how without doing any implementation changes to our app, we can enable the authentication with Azure AD. We should note that this works well if we are protecting our entire app, but what about when we need to only protect some routes and allow anonymous access to others?  The answer is provided on our next article.

Originally published by ozkary.com

10/8/16

SharePoint 2013 Missing Store App List on Custom Master Page

When adding apps on SharePoint 2013, we can add apps from our organization app catalog or the built-in apps like Tasks and Customs Lists.  This works well when using the default master page. The app selection view looks as shown below:



When applying a custom master page, we usually tend to remove some of the content containers (ContentPlaceHolder) that we may not need.  This can cause some side effects on some of the SharePoint components that may depend on those containers. In our case, we had removed one of the following items:

Server Side Markup


<asp:ContentPlaceHolder id="PlaceHolderPageTitleInTitleArea" runat="server" />

<asp:ContentPlaceHolder ID="PlaceHolderLeftNavBar" runat="server">


This created a JavaScript error which can be visible on the JavaScript console of your browser.  The end result was that part of the view was not rendered.



As shown above, the Apps you can add section is no longer visible. In some cases, the container declaration may exist, but it is set to Visible="False". This can  also cause the rendering problem.

Solution

To address this problem, we can add the tags on the master page and test the rendering of the view. The next step is to address the layout issues that this can cause on our custom master page. For that, we need to use some CSS magic to remove any of the content that we do not want displayed on our views.  An approach is to override some of the classes that are found on the inner child elements as that should not affect how the add an app section is rendered.

Hope this helps.

Originally published by ozkary.com

9/17/16

Node.js Git Deployment in Azure App Service

When deploying a node.js app to azure there are a few tools that we can use to improve the deployment experience and enable the application to start properly under IIS.   Some of these tools involve the use of Git remote repository, IISNode and Kudu dashboard.

Deployment with Git

To facilitate the deployment using Git, we need to be able to push our code from our repository to a remote repository hosted by Azure. When we create an app on Azure, there are several options for the deployment source. This is what enables continuous integration on Azure. For us, we want to focus on the Local Git Repository option. To enable it, let’s follow a few steps.

Login to your Azure console and select your app then click on Settings > Deployment Source. Click choose source and select Local Git Repository. We now need to set our deployment credentials to enable our remote login. From Settings > Deployment Source, click on Deployment credentials and type a username and password which we need to be able to push our deployment.

Now that we have configured our app and deployment source, we need to get our Git URL which is available from your app Settings > Properties > Git URL.

Copy the URL and use Git to set a remote repository on your project by typing the following Git command or using your favorite Git tool from your local repository folder. For this step to work, you should be in the folder where a local Git repo has already been created. 


git remote add myRemoteRepo https://<username>@localgitdeployment.scm.azurewebsites.net:443/localgitdeployment.git 


This command creates a remote repo reference with the name myRemoteRepo. This name can be changed to anything. We just need to remember it as it is used when pushing to the repo. We also need to replace <username> with the username that we created when setting our deployment credentials.

Now that we have our repo configuration done, we can move forward and push our deployment to Azure master branch. From your local repo folder, type this command.


Git push myRemoteRepo master


Once the code is pushed to Azure, a build process takes place which deploys the remote master branch to the application folder.  This is where a bit of magic takes place which is required for node.js app to run on Azure.

What is IISNode?

This is a module that allows node.js to run on IIS. When a deployment is done on Azure, a web.config file is created automatically with the necessary entries to allow the application to start. To better understand this, let’s take a look at a web.config that is created:


<handlers>
    <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
    <add name="iisnode" path="server.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
    <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
            <match url="^server.js\/debug[\/]?" />
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
            <action type="Rewrite" url="public{REQUEST_URI}" />
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
            <conditions>
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True" />
            </conditions>
            <action type="Rewrite" url="server.js" />
        </rule>
    </rules>
</rewrite>

As we can see in the above markup, the iisnode handler is registered with IIS. The site entry point for the application is defined by the path attribute. In this example, it uses the server.js script as the entry point for our app.  The redirect rules are for the purpose of serving the static content like images, css as well as other resources like APIs or controller calls (dynamic content).

Kudu Dashboard

To check if our application is loaded, we can use the kudu dashboard on Azure. This tool is accessible from a special Url that points to our app. We just need to add the word SCM on theURL.

App Url
Myapp.azurewebsites.net
App Url for Kudu
Myapp.scm.azurewebsites.net

To login, we can use our Azure credentials. Once the console is loaded, we can visit the process explorer area of the console. There we are able to see that in addition to the w3wp.exe, there is also the Nodejs process loaded.



I hope this article can help you on having a better understanding on the deployment of Node.js apps on Azure.

Originally published by ozkary.com