Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Token Authorization #37

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,9 @@ Issue a GET request to `/services/about`

Shown below is a fully specified configuration section for Sitecore.Ship:

<packageInstallation enabled="true" allowRemote="true" allowPackageStreaming="true" recordInstallationHistory="true">
<packageInstallation enabled="true" allowRemote="true" allowPackageStreaming="true" recordInstallationHistory="true" accessToken="some-key">
<Whitelist>
<add name="local loopback" IP="127.0.01" />
<add name="local loopback" IP="127.0.0.1" />
<add name="Allowed machine 1" IP="10.20.3.4" />
<add name="Allowed machine 2" IP="10.40.4.5" />
</Whitelist>
Expand All @@ -201,6 +201,7 @@ Default configuration:
* allowPackageStreaming = false
* recordInstallationHistory = false
* IP address whitelisting is disabled if no elements are specified below the `<Whitelist>` element or if the element is omited.
* access token is not specified and service can be used without `Authorization` HTTP header

When `recordInstallationHistory` has been set to true packages should follow the naming conventions set out below:

Expand All @@ -219,6 +220,17 @@ For example:

02-HomePage.zip

### Token based security

Service can be protected by secure access token. Every request without correct access token in its header will get `401 Unauthorized` HTTP error code.

**Important:** Token cannot protect your service without transport level security. Do not forget to use `https` when you call APIs.

Token transmition:

curl -i -H "Authorization: Bearer some-key" https://mysite/services/about


### Tools

POSTMAN is a powerful HTTP client that runs as a Chrome browser extension and greatly helps with testing test REST web services. Find out more <http://www.getpostman.com/>
Expand Down
3 changes: 3 additions & 0 deletions build/Build.proj
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@
<!-- Ship About page -->
<Exec Command="$(CurlExePath) -i $(TestWebsiteUrl)services/about" />

<!-- Test for Secure Token Authorization - add accessToken="some-key" to <packageInstallation> web.config section-->
<!-- <Exec Command="$(CurlExePath) -i -H &quot;Authorization: Bearer some-key&quot; $(TestWebsiteUrl)services/about" />-->

<!-- Install the SitecoreShip content package -->
<Exec Command="$(CurlExePath) -i --form &quot;path=@$(SitecoreShipPackagePath)&quot; $(TestWebsiteUrl)services/package/install/fileupload -F &quot;PackageId=00&quot; -F &quot;Description=Sitecore Ship package&quot;" />

Expand Down
2 changes: 1 addition & 1 deletion build/build.props
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<OutputHtmlFile>$(TestResultsPath)\TestResults.html</OutputHtmlFile>
<OutputXmlFile>$(TestResultsPath)\TestResults.xml</OutputXmlFile>
<ToolsPath>$(ProjectRoot)\tools</ToolsPath>
<XunitPath>$(ProjectRoot)\packages\xunit.1.9.2\lib\net20</XunitPath>
<XunitPath>$(ProjectRoot)\packages\xunit.runner.msbuild.2.0.0\build\portable-net45+win+wpa81+wp80+monotouch+monoandroid+Xamarin.iOS</XunitPath>
<CurlPath>$(ToolsPath)\curl</CurlPath>
<CurlExePath>$(CurlPath)\curl.exe</CurlExePath>
</PropertyGroup>
Expand Down
1 change: 1 addition & 0 deletions src/Sitecore.Ship.AspNet/BaseHttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public void ProcessRequest(HttpContext context)
if (!_authoriser.IsAllowed())
{
context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
return;
}

context.Items.Add(StartTime, DateTime.UtcNow);
Expand Down
74 changes: 74 additions & 0 deletions src/Sitecore.Ship.Core/AccessTokenAuthoriser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Sitecore.Ship.Core.Contracts;
using Sitecore.Ship.Core.Domain;

namespace Sitecore.Ship.Core
{
public class AccessTokenAuthoriser// : IAuthoriser - do not inherit from Interface to make sure that IoC dependencies resolution is not affected
{
private readonly ICheckRequests _checkRequests;
private readonly PackageInstallationSettings _packageInstallationSettings;
private readonly ILog _logger;

private const string AuthorizationHeaderKey = "Authorization";

public AccessTokenAuthoriser(ICheckRequests checkRequests,
PackageInstallationSettings packageInstallationSettings, ILog logger)
{
if (checkRequests == null)
throw new ArgumentNullException("checkRequests");
if (packageInstallationSettings == null)
throw new ArgumentNullException("packageInstallationSettings");

_checkRequests = checkRequests;
_packageInstallationSettings = packageInstallationSettings;
_logger = logger;
}

public bool IsAllowed()
{
if (!_packageInstallationSettings.TokenRequired)
return true;

if (_checkRequests.Headers == null || !_checkRequests.Headers.AllKeys.Contains(AuthorizationHeaderKey))
{
LogAccessDenial(AuthorizationHeaderKey + " header missing");
return false;
}

var allAuthorizationHeadervalues = _checkRequests.Headers.GetValues(AuthorizationHeaderKey);

// ReSharper disable once AssignNullToNotNullAttribute
string bearerHeader = allAuthorizationHeadervalues.FirstOrDefault(authorizationHeader => authorizationHeader.StartsWith("bearer", StringComparison.InvariantCultureIgnoreCase));

if (bearerHeader == null)
{
LogAccessDenial("Bearer authentication scheme required");
return false;
}

var token = bearerHeader.Substring(6).Trim();

var success = token == _packageInstallationSettings.AccessToken;

if (!success)
{
LogAccessDenial("Wrong Authentication Token");
}

return success;
}

private void LogAccessDenial(string diagnostic)
{
if (!_packageInstallationSettings.MuteAuthorisationFailureLogging)
{
_logger.Write(string.Format("Sitecore.Ship access denied: {0}", diagnostic));
}
}
}
}
6 changes: 5 additions & 1 deletion src/Sitecore.Ship.Core/Contracts/ICheckRequests.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
namespace Sitecore.Ship.Core.Contracts
using System.Collections.Specialized;

namespace Sitecore.Ship.Core.Contracts
{
public interface ICheckRequests
{
bool IsLocal { get; }

string UserHostAddress { get; }

NameValueCollection Headers { get; }
}
}
3 changes: 3 additions & 0 deletions src/Sitecore.Ship.Core/Domain/PackageInstallationSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,8 @@ public PackageInstallationSettings()
public bool MuteAuthorisationFailureLogging { get; set; }

public bool HasAddressWhitelist { get { return AddressWhitelist.Count > 0; } }

public string AccessToken { get; set; }
public bool TokenRequired { get { return !string.IsNullOrWhiteSpace(AccessToken); } }
}
}
8 changes: 8 additions & 0 deletions src/Sitecore.Ship.Core/HttpRequestAuthoriser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ public bool IsAllowed()
}
}

if (_packageInstallationSettings.TokenRequired)
{
var tokenAuthorizer = new AccessTokenAuthoriser(_checkRequests, _packageInstallationSettings, _logger);
var authorized = tokenAuthorizer.IsAllowed();
if (!authorized)
return false;
}

return true;
}

Expand Down
1 change: 1 addition & 0 deletions src/Sitecore.Ship.Core/Sitecore.Ship.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
<Compile Include="..\Common\CommonVersionInfo.cs">
<Link>Properties\CommonVersionInfo.cs</Link>
</Compile>
<Compile Include="AccessTokenAuthoriser.cs" />
<Compile Include="Contracts\IAuthoriser.cs" />
<Compile Include="Contracts\ICheckRequests.cs" />
<Compile Include="Contracts\IConfigurationProvider.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class PackageInstallationConfiguration : ConfigurationSection
const string RecordInstallationHistoryKey = "recordInstallationHistory";
const string WhitelistElementName = "Whitelist";
const string MuteAuthorisationFailureLoggingKey = "muteAuthorisationFailureLogging";
const string AccessTokenKey = "accessToken";

public static PackageInstallationConfiguration GetConfiguration()
{
Expand Down Expand Up @@ -38,6 +39,9 @@ public WhitelistCollection Whitelist

[ConfigurationProperty(MuteAuthorisationFailureLoggingKey, IsRequired = false, DefaultValue = false)]
public bool MuteAuthorisationFailureLogging { get { return (bool)this[MuteAuthorisationFailureLoggingKey]; } }

[ConfigurationProperty(AccessTokenKey, IsRequired = false, DefaultValue = "")]
public string AccessToken { get { return (string)this[AccessTokenKey]; } }
}

[ConfigurationCollection(typeof(WhitelistElement))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ public PackageInstallationConfigurationProvider()
AllowRemoteAccess = config.AllowRemoteAccess,
AllowPackageStreaming = config.AllowPackageStreaming,
RecordInstallationHistory = config.RecordInstallationHistory,
MuteAuthorisationFailureLogging = config.MuteAuthorisationFailureLogging
MuteAuthorisationFailureLogging = config.MuteAuthorisationFailureLogging,
AccessToken = config.AccessToken
};

if (config.Whitelist.Count > 0)
Expand Down
8 changes: 7 additions & 1 deletion src/Sitecore.Ship.Infrastructure/Web/HttpRequestChecker.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Web;
using System.Collections.Specialized;
using System.Web;
using Sitecore.Ship.Core.Contracts;

namespace Sitecore.Ship.Infrastructure.Web
Expand All @@ -14,5 +15,10 @@ public string UserHostAddress
{
get { return HttpContext.Current.Request.UserHostAddress; }
}

public NameValueCollection Headers
{
get { return HttpContext.Current.Request.Headers; }
}
}
}
11 changes: 11 additions & 0 deletions tests/TestUtils/TestUtils.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\xunit.runner.msbuild.2.0.0\build\portable-net45+win+wpa81+wp80+monotouch+monoandroid+Xamarin.iOS\xunit.runner.msbuild.props" Condition="Exists('..\..\packages\xunit.runner.msbuild.2.0.0\build\portable-net45+win+wpa81+wp80+monotouch+monoandroid+Xamarin.iOS\xunit.runner.msbuild.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
Expand All @@ -12,6 +13,8 @@
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
Expand Down Expand Up @@ -46,6 +49,14 @@
<Compile Include="TypeExtensions.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
<Error Condition="!Exists('..\..\packages\xunit.runner.msbuild.2.0.0\build\portable-net45+win+wpa81+wp80+monotouch+monoandroid+Xamarin.iOS\xunit.runner.msbuild.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\xunit.runner.msbuild.2.0.0\build\portable-net45+win+wpa81+wp80+monotouch+monoandroid+Xamarin.iOS\xunit.runner.msbuild.props'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
Expand Down
4 changes: 4 additions & 0 deletions tests/TestUtils/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="xunit.runner.msbuild" version="2.0.0" targetFramework="net45" />
</packages>
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\..\packages\xunit.runner.visualstudio.2.0.0-rc3-build1046\build\net20\xunit.runner.visualstudio.props" Condition="Exists('..\..\..\packages\xunit.runner.visualstudio.2.0.0-rc3-build1046\build\net20\xunit.runner.visualstudio.props')" />
<Import Project="..\..\..\packages\xunit.runner.visualstudio.2.0.0\build\net20\xunit.runner.visualstudio.props" Condition="Exists('..\..\..\packages\xunit.runner.visualstudio.2.0.0\build\net20\xunit.runner.visualstudio.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
Expand All @@ -22,7 +22,7 @@
<IISExpressUseClassicPipelineMode />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<NuGetPackageImportStamp>e34a2b6a</NuGetPackageImportStamp>
<NuGetPackageImportStamp>be5dc727</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
Expand Down Expand Up @@ -115,7 +115,7 @@
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\..\packages\xunit.runner.visualstudio.2.0.0-rc3-build1046\build\net20\xunit.runner.visualstudio.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\packages\xunit.runner.visualstudio.2.0.0-rc3-build1046\build\net20\xunit.runner.visualstudio.props'))" />
<Error Condition="!Exists('..\..\..\packages\xunit.runner.visualstudio.2.0.0\build\net20\xunit.runner.visualstudio.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\packages\xunit.runner.visualstudio.2.0.0\build\net20\xunit.runner.visualstudio.props'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Sitecore.Ship.AspNet" version="0.3.4" targetFramework="net40" />
<package id="xunit.runner.visualstudio" version="2.0.0-rc3-build1046" targetFramework="net40" />
<package id="xunit.runner.visualstudio" version="2.0.0" targetFramework="net45" />
</packages>
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<configSections>
<section name="packageInstallation" type="Sitecore.Ship.Infrastructure.Configuration.PackageInstallationConfiguration, Sitecore.Ship.Infrastructure" />
</configSections>
<packageInstallation enabled="true" allowRemote="true" allowPackageStreaming="true" recordInstallationHistory="true">
<packageInstallation enabled="true" allowRemote="true" allowPackageStreaming="true" recordInstallationHistory="true" accessToken="some-key">
<Whitelist>
<add name="Allowed machine 1" IP="1.2.3.4" />
<add name="Allowed machine 2" IP="2.3.4.5" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,11 @@ public void PackageInstallation_recordInstallationHistory_can_be_set_true()
{
_section.RecordInstallationHistory.ShouldBeTrue();
}

[Fact]
public void PackageInstallation_accessKey_can_be_set()
{
_section.AccessToken.ShouldEqual("some-key");
}
}
}
Loading