Skip to content
This repository has been archived by the owner on Jan 17, 2024. It is now read-only.

Commit

Permalink
Merge pull request #145 from AppliedIS/config-ssl
Browse files Browse the repository at this point in the history
Config ssl
  • Loading branch information
klinden committed Nov 16, 2016
2 parents b4dc0e8 + a89db30 commit cf0e763
Show file tree
Hide file tree
Showing 23 changed files with 144 additions and 46 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Configuration;
using System.Web.Http;
using System.Web.Http;
using DOL.WHD.Section14c.Business;
using DOL.WHD.Section14c.Business.Factories;
using DOL.WHD.Section14c.Business.Services;
using DOL.WHD.Section14c.Business.Validators;
using DOL.WHD.Section14c.Common;
using DOL.WHD.Section14c.DataAccess;
using DOL.WHD.Section14c.DataAccess.Repositories;
using SimpleInjector;
Expand All @@ -23,7 +23,7 @@ public static void Register()
container.Register<ISaveRepository, SaveRepository>(Lifestyle.Scoped);
container.Register<ISaveService, SaveService>(Lifestyle.Scoped);
container.Register<IIdentityService, IdentityService>(Lifestyle.Scoped);
container.Register<IFileRepository>(() => new FileRepository(ConfigurationManager.AppSettings["AttachmentRepositoryRootFolder"]), Lifestyle.Scoped);
container.Register<IFileRepository>(() => new FileRepository(AppSettings.Get<string>("AttachmentRepositoryRootFolder")), Lifestyle.Scoped);
container.Register<IApplicationRepository, ApplicationRepository>(Lifestyle.Scoped);
container.Register<IApplicationService, ApplicationService>(Lifestyle.Scoped);
container.Register<IApplicationSummaryFactory, ApplicationSummaryFactory>(Lifestyle.Scoped);
Expand Down
6 changes: 6 additions & 0 deletions DOL.WHD.Section14c.Api/App_Start/RouteConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Help Area",
"",
new { controller = "Help", action = "Index" }
).DataTokens = new RouteValueDictionary(new { area = "HelpPage" });

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
Expand Down
13 changes: 4 additions & 9 deletions DOL.WHD.Section14c.Api/App_Start/Startup.Auth.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
using System;
using System.Configuration;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using DOL.WHD.Section14c.Api.Providers;
using DOL.WHD.Section14c.Common;
using DOL.WHD.Section14c.DataAccess;
using DOL.WHD.Section14c.DataAccess.Identity;
using DOL.WHD.Section14c.Domain.Models.Identity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
Expand All @@ -36,7 +32,7 @@ public void ConfigureAuth(IAppBuilder app)
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
ExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireTimeSpanMinutes"])),
ExpireTimeSpan = TimeSpan.FromMinutes(AppSettings.Get<double>("AccessTokenExpireTimeSpanMinutes")),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = ctx =>
Expand Down Expand Up @@ -67,9 +63,8 @@ public void ConfigureAuth(IAppBuilder app)
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireTimeSpanMinutes"])),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = false
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(AppSettings.Get<double>("AccessTokenExpireTimeSpanMinutes")),
AllowInsecureHttp = !AppSettings.Get<bool>("RequireHttps")
};

app.Use(async (context, next) =>
Expand Down
7 changes: 2 additions & 5 deletions DOL.WHD.Section14c.Api/Areas/HelpPage/Views/Help/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
@model Collection<ApiDescription>

@{
ViewBag.Title = "DOL WHD Section 14c API Help";
ViewBag.Title = "DOL.WHD.Section.14c.API";

// Group APIs by controller
ILookup<HttpControllerDescriptor, ApiDescription> apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor);
Expand All @@ -23,10 +23,7 @@
<div id="body" class="help-page">
<section class="featured">
<div class="content-wrapper">
<h2>Introduction</h2>
<p>
Provide a general description of your APIs here.
</p>
Version: @typeof(DOL.WHD.Section14c.Api.WebApiApplication).Assembly.GetName().Version
</div>
</section>
<section class="content-wrapper main-content clear-fix">
Expand Down
6 changes: 3 additions & 3 deletions DOL.WHD.Section14c.Api/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
Expand All @@ -18,6 +17,7 @@
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity;
using DOL.WHD.Section14c.Common;
using DOL.WHD.Section14c.Domain.Models.Identity;

namespace DOL.WHD.Section14c.Api.Controllers
Expand Down Expand Up @@ -56,8 +56,8 @@ public async Task<IHttpActionResult> Register(RegisterViewModel model)
}

// Validate Recaptcha
var reCaptchaVerfiyUrl = ConfigurationManager.AppSettings["ReCaptchaVerfiyUrl"];
var reCaptchaSecretKey = ConfigurationManager.AppSettings["ReCaptchaSecretKey"];
var reCaptchaVerfiyUrl = AppSettings.Get<string>("ReCaptchaVerfiyUrl");
var reCaptchaSecretKey = AppSettings.Get<string>("ReCaptchaSecretKey");
if (!string.IsNullOrEmpty(reCaptchaVerfiyUrl) && !string.IsNullOrEmpty(reCaptchaSecretKey))
{
var remoteIpAddress = Request.GetOwinContext().Request.RemoteIpAddress;
Expand Down
4 changes: 4 additions & 0 deletions DOL.WHD.Section14c.Api/DOL.WHD.Section14c.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,10 @@
<Project>{7cd1d7dd-ce24-4280-b8bd-0b8b9abb0ffc}</Project>
<Name>DOL.WHD.Section14c.Business</Name>
</ProjectReference>
<ProjectReference Include="..\DOL.WHD.Section14c.Common\DOL.WHD.Section14c.Common.csproj">
<Project>{9C06ABE3-28D2-4BAB-BAA4-11B6C404B329}</Project>
<Name>DOL.WHD.Section14c.Common</Name>
</ProjectReference>
<ProjectReference Include="..\DOL.WHD.Section14c.DataAccess\DOL.WHD.Section14c.DataAccess.csproj">
<Project>{F7033F89-ED1B-4784-AEAB-D8808FBBEC92}</Project>
<Name>DOL.WHD.Section14c.DataAccess</Name>
Expand Down
9 changes: 5 additions & 4 deletions DOL.WHD.Section14c.Api/Filters/AuthorizeHttps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,15 @@
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using DOL.WHD.Section14c.Common;

namespace DOL.WHD.Section14c.Api.Filters
{
public class AuthorizeHttps : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (SkipAuthorization(actionContext))
return;

if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps && AppSettings.Get<bool>("RequireHttps"))
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
Expand All @@ -22,6 +20,9 @@ public override void OnAuthorization(HttpActionContext actionContext)
}
else
{
if (SkipAuthorization(actionContext))
return;

base.OnAuthorization(actionContext);
}
}
Expand Down
4 changes: 3 additions & 1 deletion DOL.WHD.Section14c.Api/Parameters.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,7 @@
<parameter name="EmailFrom" defaultValue="no-reply@dol.gov">
<parameterEntry kind="XmlFile" scope="web\.config$" match="/configuration/system.net/mailSettings/smtp/@from" />
</parameter>

<parameter name="RequireHttps" defaultValue="true">
<parameterEntry kind="XmlFile" scope="web\.config$" match="/configuration/appSettings/add[@key='RequireHttps']/@value" />
</parameter>
</parameters>
7 changes: 2 additions & 5 deletions DOL.WHD.Section14c.Api/Providers/ApplicationOAuthProvider.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using DOL.WHD.Section14c.DataAccess.Identity;
using DOL.WHD.Section14c.Domain.Models;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using System.Linq;
using DOL.WHD.Section14c.Domain.Models.Identity;
using DOL.WHD.Section14c.Common;

namespace DOL.WHD.Section14c.Api.Providers
{
Expand All @@ -38,7 +35,7 @@ public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwner
if (user != null)
{
var passwordExpired = false;
var passwordExpirationDays = Convert.ToInt32(ConfigurationManager.AppSettings["PasswordExpirationDays"]);
var passwordExpirationDays = AppSettings.Get<int>("PasswordExpirationDays");
if (passwordExpirationDays > 0)
{
passwordExpired = user.LastPasswordChangedDate.AddDays(passwordExpirationDays) < DateTime.Now;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
using System;
using System.Configuration;
using System.IO;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using DOL.WHD.Section14c.Common;

namespace DOL.WHD.Section14c.Api.Providers
{
public class RestrictedMultipartMemoryStreamProvider : MultipartMemoryStreamProvider
{
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
var pattern = ConfigurationManager.AppSettings["AllowedFileNamesRegex"];
var pattern = AppSettings.Get<string>("AllowedFileNamesRegex");
var fileNameRegex = new Regex(pattern);
var fileName = headers.ContentDisposition.FileName;

Expand Down
1 change: 1 addition & 0 deletions DOL.WHD.Section14c.Api/Web.config
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
<add key="ReCaptchaSecretKey" value="6LeqeggUAAAAAEY5KpgWZGkOHnkyQXmiSKg7tqsY" /> <!-- If key is not provided, server-side ReCaptcha validation is disabled -->
<add key="AttachmentRepositoryRootFolder" value="C:\temp\DOL-WHD-Section14c-Attachments\"/>
<add key="AllowedFileNamesRegex" value="^(.*\.(doc|docx|xls|xlsx|pdf|jpg|jpeg|png)$)?[^.]*$" />
<add key="RequireHttps" value="true" />
</appSettings>
<!--
For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.
Expand Down
17 changes: 17 additions & 0 deletions DOL.WHD.Section14c.Common/AppSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.ComponentModel;
using System.Configuration;

namespace DOL.WHD.Section14c.Common
{
public static class AppSettings
{
public static T Get<T>(string key)
{
var appSetting = ConfigurationManager.AppSettings[key];
if (string.IsNullOrWhiteSpace(appSetting)) throw new SettingsPropertyNotFoundException(key);

var converter = TypeDescriptor.GetConverter(typeof(T));
return (T)(converter.ConvertFromInvariantString(appSetting));
}
}
}
2 changes: 2 additions & 0 deletions DOL.WHD.Section14c.Common/DOL.WHD.Section14c.Common.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
Expand All @@ -43,6 +44,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AppSettings.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,10 @@
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DOL.WHD.Section14c.Common\DOL.WHD.Section14c.Common.csproj">
<Project>{9C06ABE3-28D2-4BAB-BAA4-11B6C404B329}</Project>
<Name>DOL.WHD.Section14c.Common</Name>
</ProjectReference>
<ProjectReference Include="..\DOL.WHD.Section14c.Domain\DOL.WHD.Section14c.Domain.csproj">
<Project>{CAE5367B-F6CD-440F-9524-5AE43A38116E}</Project>
<Name>DOL.WHD.Section14c.Domain</Name>
Expand Down
11 changes: 5 additions & 6 deletions DOL.WHD.Section14c.DataAccess/Identity/IdentityConfig.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
using System;
using System.Configuration;
using System.Threading.Tasks;
using DOL.WHD.Section14c.Common;
using DOL.WHD.Section14c.DataAccess.Validators;
using DOL.WHD.Section14c.Domain.Models;
using DOL.WHD.Section14c.Domain.Models.Identity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
Expand Down Expand Up @@ -44,17 +43,17 @@ public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUs
};

// Configure lockout
manager.UserLockoutEnabledByDefault = Convert.ToBoolean(ConfigurationManager.AppSettings["UserLockoutEnabledByDefault"]);
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(Double.Parse(ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"]));
manager.MaxFailedAccessAttemptsBeforeLockout = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"]);
manager.UserLockoutEnabledByDefault = AppSettings.Get<bool>("UserLockoutEnabledByDefault");
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(AppSettings.Get<double>("DefaultAccountLockoutTimeSpan"));
manager.MaxFailedAccessAttemptsBeforeLockout = AppSettings.Get<int>("MaxFailedAccessAttemptsBeforeLockout");

var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"))
{
//Code for email confirmation and reset password life time
TokenLifespan = TimeSpan.FromHours(Double.Parse(ConfigurationManager.AppSettings["EmailVeriryAndPaswordRestTokenExpireHours"]))
TokenLifespan = TimeSpan.FromHours(AppSettings.Get<double>("EmailVeriryAndPaswordRestTokenExpireHours"))
};
}
return manager;
Expand Down
2 changes: 1 addition & 1 deletion DOL.WHD.Section14c.Test/Business/SaveServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class SaveServiceTests
public SaveServiceTests()
{
_saveRepositoryMock = new SaveRepositoryMock();
_fileRepositoryMock = new FileRepository("TestUploads");
_fileRepositoryMock = new FileRepository(@"TestUploads\");
}

[TestMethod]
Expand Down
51 changes: 51 additions & 0 deletions DOL.WHD.Section14c.Test/Common/AppSettingsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System.Configuration;
using DOL.WHD.Section14c.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DOL.WHD.Section14c.Test.Common
{
[TestClass]
public class AppSettingsTests
{
[TestMethod]
[ExpectedException(typeof(SettingsPropertyNotFoundException))]

public void SetttingNotAvailable()
{
AppSettings.Get<bool>("unknown");
}

[TestMethod]

public void SetttingConfigured_ReturnsCorrectBool()
{
var results = AppSettings.Get<bool>("BoolConfig");
Assert.AreEqual(results, true);
}

[TestMethod]

public void SetttingConfigured_ReturnsInt()
{
var results = AppSettings.Get<int>("IntConfig");
Assert.AreEqual(results, 1);
}

[TestMethod]

public void SetttingConfigured_ReturnsString()
{
var results = AppSettings.Get<string>("StringConfig");
Assert.AreEqual(results, "value");
}

[TestMethod]

public void SetttingConfigured_ReturnsDouble()
{
var results = AppSettings.Get<double>("DoubleConfig");
Assert.AreEqual(results, 123.4);
}

}
}
5 changes: 5 additions & 0 deletions DOL.WHD.Section14c.Test/DOL.WHD.Section14c.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
<Compile Include="Business\Validators\WIOAWorkerValidatorTests.cs" />
<Compile Include="Business\Validators\WorkerCountInfoValidatorTests.cs" />
<Compile Include="Business\Validators\WorkSiteValidatorTests.cs" />
<Compile Include="Common\AppSettingsTests.cs" />
<Compile Include="Domain\BaseEntityTests.cs" />
<Compile Include="Domain\Models\FeatureTests.cs" />
<Compile Include="Domain\Models\Identity\ApplicationUserRoleTests.cs" />
Expand Down Expand Up @@ -159,6 +160,10 @@
<Project>{7cd1d7dd-ce24-4280-b8bd-0b8b9abb0ffc}</Project>
<Name>DOL.WHD.Section14c.Business</Name>
</ProjectReference>
<ProjectReference Include="..\DOL.WHD.Section14c.Common\DOL.WHD.Section14c.Common.csproj">
<Project>{9C06ABE3-28D2-4BAB-BAA4-11B6C404B329}</Project>
<Name>DOL.WHD.Section14c.Common</Name>
</ProjectReference>
<ProjectReference Include="..\DOL.WHD.Section14c.DataAccess\DOL.WHD.Section14c.DataAccess.csproj">
<Project>{f7033f89-ed1b-4784-aeab-d8808fbbec92}</Project>
<Name>DOL.WHD.Section14c.DataAccess</Name>
Expand Down
11 changes: 10 additions & 1 deletion DOL.WHD.Section14c.Test/app.config
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,13 @@
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>
<appSettings>
<add key="BoolConfig" value="true" />
<add key="IntConfig" value="1" />
<add key="StringConfig" value="value" />
<add key="DoubleConfig" value="123.4" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>
Loading

0 comments on commit cf0e763

Please sign in to comment.