Pages

Saturday, March 23, 2013

Encrypting ASP.Net Application Settings

When storing sensitive information in our web.config files, we may want to keep this information secured by encrypting the settings. We can easily do this by using the ASP.NET IIS registration tool (aspnet_regiis.exe) found in the Visual Studio command prompt. This tools allows us to encrypt our settings by just using a couple of command lines, but there are a few things that we should know before we start encrypting our configuration settings.
  • Encryption is done at the section level not setting
  • Uses the current machine key for encryption

Section Level Encryption

This tool allows us to encrypt an entire section not just an entry. If our settings are in the appSettings section, any other settings in this section will also be encrypted. If we need the ability to have clear text settings, we may not want to use this section. The reason for this is because the entire section is changed to an XML structure that is encrypted data. To illustrate this, let’s encrypt the following section:

  <appSettings>
    <add key="Password" value="12345789"/>   
  </appSettings>

By running the following command using the Visual Studio command prompt (under the Visual Studio Tools menu):

aspnet_regiis.exe -pef appSettings "C:\myfolder"

This command basically indicates that we want to encrypt (-pef) a section (appSettings) using a physical path (mypath) . By default, the tool looks for a web.config file within the folder.  There is also support for virtual directories using -pe.

After the command is successful, our settings are encrypted and changed to the following format:

<appSettings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
      xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <KeyName>Rsa Key</KeyName>
          </KeyInfo>
          <CipherData>
            <CipherValue>Lyx2UzIumZmg/MRAUPn/Vr1K5grmHlgyqSzvb5qk23SdsGrZWEZ5TinhxUFGVOr12cSTJsAzuGbpiDqUvuP/W/EqS+p4bRybKzNioVhwLK+tb8sm3o0XpIPHEQFVOzKRtPzPznBvzfVK0HPF1FF9+T2gkoDoae2UzDFfX3duKM0=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>srK0/WwBH60H2jjl62waDnt9MZeOfgVqdwsXVsp2MQe0gtIbSd8LZtjZXIdDCom/1T7oVn+Fped7YwqaQA84no2yl211aw3vluRdPeaud0FfDz6pLgimzA==</CipherValue>
      </CipherData>
    </EncryptedData>
  </appSettings>

All the entries under the appSettings are combined in the EncryptedData section. The framework takes care of the decryption when we use the Configuration Settings API, so the code does not have to change. If we need to see what the value is for a particular setting, we need to decrypt the section. To do this, we just need to run this command (Visual Studio command prompt):

aspnet_regiis.exe -pdf appSettings "C:\myfolder"

*Note that we are now using –pdf to decrypt the section
.
Encrypt Application Settings

A better approach to encrypt settings with sensitive information is to add application settings to your project. This adds a custom section that can be independently encrypted. For example, we can add an application setting to our project by using Visual Studio Add New Item – Settings File and add the Password setting.  Visual Studio generates a new setting section in our configuration file like the one below:

<applicationSettings>
    <Encrypt.App>
      <setting name="Password" serializeAs="String">
        <value>123456789</value>
      </setting>
    </Encrypt.App>
  </applicationSettings>

The section that we need to encrypt is under the applicationSettings element. Since we now have an isolated section, we just need to encrypt the Encrypt.App section without messing other settings. We can do this by running this command:

aspnet_regiis.exe -pef applicationSettings/Encrypt.App "C:\myfolder"

When running the command, we use the applicationSettings/Encrypt.App XPath to only encrypt the custom section. This allows us to isolate the encryption to the one section thus enabling us to add other application sections with clear text. The decryption is done by the framework, and it is transparent to the code.

Our section gets encrypted and looks as follows:

<applicationSettings>
    <Encrypt.App configProtectionProvider="RsaProtectedConfigurationProvider">
      <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
        xmlns="http://www.w3.org/2001/04/xmlenc#">
 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
        <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
          <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
   <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
            <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
              <KeyName>Rsa Key</KeyName>
            </KeyInfo>
            <CipherData>
              <CipherValue>Q818+69UTEO7SSn1+ll7kwZQuklVdR3lZu6nGsPdfnXmOxfqeyaGr+hJ9Ieuao0XFTD/Bv4QjYODxlsdUpre+VjeG3IugvsKzbngB9naRAS7pn9a4OUrQGa1f03Tvo7z103TyMAAyZZNEb+BQTfOqArxxVO6iMM2Fgoc7d//VEQ=</CipherValue>
            </CipherData>
          </EncryptedKey>
        </KeyInfo>
        <CipherData>
          <CipherValue>usKSkMsAfuPZHvyieiru1Nh9xlYDy9HryOmxHQPgCu8s4HJ1y/zfmtV7uM4ywV1+AIrBHt8l4GhL5KK+1HMbWjpcB/VC17vyTt6Mv7eEL7hDO5ASYQ2Zxsxiw6rnASK3jn5WqDQuA+WDUF7ZvE8rJPqJlydISyn97pspIxqQd+Y+rwAOq/+I87oXFmlMEZWk</CipherValue>
        </CipherData>
      </EncryptedData>
    </Encrypt.App>
  </applicationSettings>

We should note that the Encrypt.App section has an attribute (configProtectionProvider) which indicates that only that section is encrypted, and the applicationSettings (element) is not affected.

Machine Key

When we use this approach, we must be aware that the encryption is done using the current machine key. This means that if we encrypt this setting on the development box, we cannot just copy the encrypted setting to another machine because a different key would be used during the decryption process of the settings, and this would fail.

 We will need to be mindful that the encryption needs to be done in each box where this needs to be supported, so before taking this approach we must make sure that this is not a problem with the teams that support all the different environments. 

I hope this article provides you with the tools to help you make sure settings secure.


Sunday, February 24, 2013

CRM Dynamic Outlook Client Does Not Authenticate


After installing the CRM Dynamics Outlook client, you may see an error indicating that your credentials can't be authenticated by the CRM service even when you know that your credentials are correct.

   

When this takes place, we need to look at what service your work station is trying to connect. When prompted by the configuration dialog, we should select the CRM Online entry. This allows the plugin to try to connect to  disco.crm.dynamics.com. This is the url where the client should get authenticated. 

If even after selecting this option, you are still unable to login. You would need to reset the generic credentials that are stored in your system because there may be a caching issue with an invalid credential.  To do this, follow these steps:

  • Click on Control Panel
  • Click on User Accounts
  • Click on Manage your credentials

We should now look at the Generic Credentials section.There is a list of credentials that end with the crm.dynamics.com domain name. You can expand the list and see what kind of credentials are being used.




The best way to clean this up is to expand each entry and remove it from the vault.  This way we can start the CRM configuration wizard again and select CRM online for the server URL option.  Once the credentials have been accepted, we should be able to see the organization name from the list. At this point, the connection should be successful and the CRM plugin on Outlook should be working as expected.

 I hope this saves you some time and resolves this problem.

Sunday, January 27, 2013

Cross Domain Support With Web API


As we know, cross-site HTTP requests from scripts are restricted due to security reasons.  Basically, if our web application runs on a domain (myapp.com), and we try to make a web service call via AJAX to a different domain (myservice.com), we get a cross domain error (not allowed). In the world of Web API and web services in general, we have the need to support cross domain requests because we may be building a service layer with the purpose to be consumed by multiple web applications with different domains.

This need has been identified by the WebApps Working Group which is part of the W3C, and the Cross-Origin Resource Sharing (CORS) recommendation was made. This allows us to enable web services to support cross-site HTTP requests.

A way to address this for Web API is to create a delegating handler that can authorize the request from different domains. Lucky for us, there is already a NuGet package that can be installed on our project. To install it, we can just enter the following on the Package Manager Console:

PM> Install-Package Thinktecture.IdentityModel

Once this handler is installed, we just need to register the CORS support in our global.asax Application_Start event handler. This can be done with the following snippet:

using Thinktecture.IdentityModel.Http.Cors.WebApi;

protected void Application_Start()
{
...
CrossOriginResourceSharing(GlobalConfiguration.Configuration);
}


void CrossOriginResourceSharing(HttpConfiguration httpConfig)
{
       string origin = "CrossDomainUrl"; 
       if (!String.IsNullOrWhiteSpace(origin))
       {
           var corsConfig = new WebApiCorsConfiguration();
           corsConfig.RegisterGlobal(httpConfig);   
           corsConfig.ForOrigins(origin).AllowAll();
       }
}

 In this code, we are just setting one single domain in the ForOrigins method, but there is support for multiple domains. We are also allowing cross domain access for all the resources, but if we need to allow access to only one resource/controller, we can use this method instead:

corsConfig.ForResources("Controller1").ForOrigins(origin).AllowAll();

If we need to control the methods (GET/POST), we can also use the following:

corsConfig.ForOrigins(origin).AllowMethods("GET").AllowAll();

One more thing to note is that this library also supports ASP.NET MVC and Web Forms application. For those web applications, the implementation is done with an HTTP module, so in addition to registering the CORS support, we also need to add the Module setting in the web.config file.

I hope this article is able to give you some understanding on how to address Cross-Domain access for Web API services. There is more information to learn about this library, so I advise to read more about it and learn all the capabilities that are available.

Web API Serialize ENUM Types as String


By default, Web API serializes ENUM data types to the numeric value. For some applications, it would be better to use the string representation instead of the number. An example would be when using  a JavaScript template framework which prevents the need to add implementation code to map the numbers to labels. But before we go crazy and start changing all the model definitions, we should know that there is a way to handle this at the application level.

To address this, we need to add a Media Type Formatter. In Web API, the media type determines how to serialize the data with a built-in support for JSON, XML and form-urlencoded.

The following helper method handles the configuration of the media formatter setting. This code should be added in the global.asax.cs file.

using Newtonsoft.Json;

protected void Application_Start()
{
   SerializeSettings(GlobalConfiguration.Configuration);
                
}


void SerializeSettings(HttpConfiguration config)
{
   JsonSerializerSettings jsonSetting = new JsonSerializerSettings();
   jsonSetting.Converters.Add(new Converters.StringEnumConverter());
   config.Formatters.JsonFormatter.SerializerSettings = jsonSetting;
}

The json serializer setting is configured with a converter which handles the serialization of ENUMs to strings (StringEnumConverter). This setting is then added to the application media formatter collection. This setting is then applied to any of the serialization that takes places during an API call, and the ENUM values should now reflect the string value instead of the number.

We can test this by using a developer's tool like fiddler and look at the JSON raw data that comes back from a WEB API request.

Saturday, January 5, 2013

Copy Office 365 files to Local Disk


So we are done building your Office 365 website, and we would like to save a copy of the files to a local disk. We open SharePoint Designer and realized that we are able to see the files and folders. However we are not able to just right click and save the files to a Windows directory.  What do we do know?

In order to be able to copy files from Office 365 to Windows explorer, we need to map the Office 365 website to a local drive. This allows Windows explorer to navigate the folder structure as if the files are local to the computer.  Once this is done, we can copy the files from the Office 365 website to a local drive.

How to map Office 365 to a local drive:
  • Open Windows Explorer
  • Right-click on Network and then click Map Network Drive
  • Click on a link (bottom) that reads “Connect to a Web site that you can store your documents and pictures”
  • Click Next
  • Select Choose a custom network location and click next
  • Enter the full path to your website. Similar to http://www.mysite.com and check Connect using different credentials
  • Enter your office 365 credentials
Once mapped, you can now use Windows explorer to see all the files and directories. You can now copy  and save the files in your local directory.


As a side note, you can also save your website as a template. The template is saved as a single file that contains all the content (.aspx, master pages, and images) files. In order to see the individual files, you would need to open the file using Visual Studio 2010 or newer.

Saturday, December 15, 2012

SharePoint Designer 2010 how to change the current user


When using SharePoint Designer 2010 to connect to a SharePoint and SharePoint online website, the application prompts the user to login for the first time. After the user has logged on once, the application caches this information and automatically logins to the website the next time you try to open the website. This is a desirable feature, but there is often the case when we want to login as a different user, and SharePoint Designer continues to auto login with the credentials already cached.

To be able to login as a different user, one needs to first let the application automatically login to the website. Once the website is open on the designer, there is a face icon on the bottom-left of the application as shown below:

Click to change user

If you click on the icon, the application displays a dialog indicating that you are logged on as a particular user and if you want to login as someone else. Click ok, and enter the new credentials. This should allow you to login as a different user, and you can go on with your tasks.

Saturday, November 10, 2012

Office 365 Public Website Branding

Office 365 provides by default a public website which is usually located at an URL similar to this:


The pages folder is already set up with public permissions. This allows the site to be visited by non-authenticated users. The pages on this site are created with the root.master page. This master page can’t be modified to brand our site. The main reason is because there is a WYSIWYG editor available for these pages that allow you customize the site with predefined styles and themes. Any attempts to modify the root.master files would cause the website to break.

How do I brand my Office 365 website?

Depending on your expertise on web design and SharePoint Online (This is on what Office 365 is built on); you can brand an Office 365 with the following options:

Option 1 – Default Public website with WYSIWYG editor

Use the default public website with the default themes and styles right from the browser. This is the easiest approach, and it will deliver a basic website design with a basic layout and theme. You will be able to add a header, footer and navigation menus. We can also change the layout structure by adding different zones to the page. We can also add page title, description and keyword Meta tags to aid on SEO. Most people are really not happy with the results they get from this option.

Option 2- Public website with CSS and JavaScript.

This option allows you to use option 1 as the baseline with further customization with the use of CSS and JavaScript. Office 365 allows us to apply a custom style sheet to the website. With this style sheet, we can control many of the design elements of the website. For example, we can customize the header, footer and menu with background images and different layout effects. If we need to add other HTML elements to the web pages, we can include JavaScript with the use of a PayPal gadget (hack to avoid using the HTML gadget which uses iframes). This lets us add HTML into the page with the use of a XSL template. This option requires experience in website design and development, but it provides a lot more flexibility on the design. The main problem here is that we are still bound to using the root.master page.

Option 3 – Public Website with SharePoint Designer

When the first two options are not providing all the flexibility you need, you can now start using SharePoint Designer. This is a developer tool that allows us to open an Office 365 site and have more control over the design of the site. We can open the website pages with this editor and fully customize the HTML (within the Container tags that are required by the master page). Once we start doing customization at this level, the WYSIWYG editor on the browser will no longer work. This approach makes designer and developers happy because there is more control on the design and folder structure of the website without the need to know SharePoint specifics.

Option 4 – Create pages with a different master page and SharePoint Designer

If you are ready to move away from the root.master file, this is the approach for you. With SharePoint Designer, we can attach pages to a different master file. This master file can be customized to meet all of our design needs. For example, we can create a HTML5 master template with all the branding requirements and attach the new pages to this new master template.  This however increases the complexity level because your master page needs to meet a few requirements to be a valid SharePoint master page. At this level, SharePoint knowledge starts to become a dependency. There are however a few basic templates that can be used as a starting point.

Option 5 – Create a new sub site and make this your public website with SharePoint Designer

Office 365 allows us to create sub-sites which are created private by default. We can however change the access setting and make it public. Once we make a sub-site public, we can set any page in the sub-site as the site home page (this is a global site setting).  This tells SharePoint that when a person navigates to your domain http://mydomain.com that the browser should be redirected to the home page which now resides at the new sub-site. This is how it works for the default public website. SharePoint basically redirects users to http://mydomain.com/pages/default.aspx. For a sub-site, SharePoint redirects the users to something like: http://mydomain.com/sitepages/home.aspx.

With this approach, you now need to know more about SharePoint administration and development. The benefits are that we can now integrate SharePoint features to the public website. For example, we can display a document library, calendar, lists, custom web-parts and custom business solutions. For public users to create new records in a list, you will need to explicitly provide public write access to that list.

Main Difference between SharePoint on premises VS SharePoint online

The main difference between SharePoint on Premises and online is that you can only deployed Sandboxed solutions on the online edition.  A Sandboxed solution is isolated, and SharePoint will block it if the solution starts to become unstable. The reason behind this is because this is a Multi-tenant environment, and it is not convenient to have one tenant’s solutions affect other tenant’s sites.  This also implies that certain resources are not available for a Sandboxed solution compare to a Farm Solution which limits what you can do for your custom solutions.

Summary

SharePoint branding is not as easy as a normal HTML website, and depending on your skill set, you may choose any of the listed options above. If you are not familiar with SharePoint, you may want to partner with a company that has this expertise. I hear from many designers and a developer how frustrating is to work with this product, but like anything, certain level of expertise is required to know how to work with a particular technology.

 I hope I was able to show you a few approaches on how to brand your SharePoint public website.