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

Develop to Main - publish 2.0.0 #21

Merged
merged 36 commits into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
ac5d34e
configure what host is allowed through
floyd-may Apr 27, 2022
66e0bba
fix origin/Develop check in GH action
floyd-may Apr 29, 2022
9371b47
random syntax issue in GH action
floyd-may Apr 29, 2022
667ccfe
schrodingbug in GH action config - how did that ever work?
floyd-may Apr 29, 2022
3af6d96
only push to nuget if on origin/Develop
floyd-may Apr 30, 2022
37b1a14
retry only push to nuget if on origin/Develop
floyd-may Apr 30, 2022
87ef7ce
fix syntax error
floyd-may Apr 30, 2022
6b3e0b1
I'm a programmer, i understand booleans. really.
floyd-may Apr 30, 2022
50efb3c
allow multiple allowed hosts
floyd-may Apr 30, 2022
fdf99e5
bumping the version. Offically kicks of the 2.0 RC. Still need to cut…
calebjenkins May 1, 2022
dfa039d
Merge pull request #11 from calebjenkins/allow-non-localhost
calebjenkins May 1, 2022
0b5160c
fix CI actions workflow
floyd-may May 1, 2022
628c792
Merge pull request #14 from calebjenkins/ci-publish-nuget
calebjenkins May 1, 2022
c8325c4
build nuget for both netcoreapp3.1 and net6.0
floyd-may May 1, 2022
eed43bf
remove unneeded conditional package refs
floyd-may May 1, 2022
ee61fb3
made test HostRewriteSettings.Host string? to rmove compiler warning.
calebjenkins May 1, 2022
9a460d9
moved FakeAuth setting List<Claims> to IList<Claims for consistancy.
calebjenkins May 1, 2022
ee27059
removing obsolete extension methods
calebjenkins May 1, 2022
33b153d
update to readme for 2.0.0
calebjenkins May 1, 2022
4014740
update samples to CI nuget and StartUp class
calebjenkins May 2, 2022
f24ea7d
Merge pull request #15 from calebjenkins/update-nuget-targeting
calebjenkins May 2, 2022
375bb4e
Merge branch 'Develop' into dev/feature-12-Prep-for-2.0
calebjenkins May 2, 2022
be0b266
adding net5 to nuget targets and updating readme with additonal links
calebjenkins May 2, 2022
66079c2
Merge pull request #16 from calebjenkins/dev/feature-12-Prep-for-2.0
calebjenkins May 2, 2022
cd771eb
re-arranging net6 vs net 5 - only net 5 was showing up in nuget
calebjenkins May 2, 2022
3afc586
can't get 5.0 and 6.0 to both show in nuget. screw it, only care abou…
calebjenkins May 2, 2022
f5430a3
update readme format for History
calebjenkins May 2, 2022
670d9d0
additonal context in readme history
calebjenkins May 2, 2022
69e1fc0
moving IEnumerable to IList for ApprovedHosts
calebjenkins May 2, 2022
ce2b550
Merge pull request #18 from calebjenkins/dev/feature-13-evaluating-2.0
calebjenkins May 2, 2022
0423e4a
update samples to always reference latest CI nuget package to catch i…
calebjenkins May 2, 2022
99e1975
Merge pull request #19 from calebjenkins/dev/feature-14-move-nuget-sa…
calebjenkins May 2, 2022
9f884d3
adding AllowedHosts to SampleWeb App comments
calebjenkins May 3, 2022
b323166
Merge pull request #20 from calebjenkins/dev/feature-15-final-2.0-eval
calebjenkins May 3, 2022
43b5079
Updating wf to fix error. Using Floyd-fu from dev-ci and pplying to main
calebjenkins May 3, 2022
575f016
Merge branch 'Develop' of https://github.com/calebjenkins/FakeAuth in…
calebjenkins May 3, 2022
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
21 changes: 16 additions & 5 deletions .github/workflows/dev-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ on:
- '**.md'
workflow_dispatch:

env:
Nuget_Key: secrets.FAKEAUTH_NUGET_KEY
Nuget_URL: "https://api.nuget.org/v3/index.json"
env:
Nuget_Key: secrets.FAKEAUTH_NUGET_KEY
Nuget_URL: "https://api.nuget.org/v3/index.json"

jobs:
build:
Expand Down Expand Up @@ -78,13 +78,24 @@ jobs:
- name: Test
run: dotnet test --configuration Release --no-build

- name: Verify commit exists in origin/Develop
run: git branch --remote --contains | grep origin/Develop
- name: Verify is based on origin/Develop
# List commits that are ahead of origin/Develop through HEAD and look for the tip of the current branch.
# If HEAD isn't ahead of origin/Develop, the git log bit will be empty and grep will fail
run: git log origin/Develop..HEAD | grep $(git rev-parse --short HEAD)


- name: Detect if workflow is running on origin/Develop
id: detect_develop
run: git rev-parse HEAD | grep $(git rev-parse origin/Develop)
continue-on-error: true


- name: Pack
run: dotnet pack --configuration Release /p:Version=${{steps.get_version.outputs.RELEASE_VERSION}}-ci-${BUILD_NUMBER} --include-symbols --output .
if: ${{ steps.detect_develop.outcome == 'success' }}


- name: Push to Nuget
if: ${{ steps.detect_develop.outcome == 'success' }}
# run: dotnet nuget push *.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{secrets.FAKEAUTH_NUGET_KEY}}
run: dotnet nuget push FakeAuth.${{steps.get_version.outputs.RELEASE_VERSION}}-ci-${BUILD_NUMBER}.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{secrets.FAKEAUTH_NUGET_KEY}}
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ client.SetFakeAuthClaims(
);
```

You can also re-use any profiles that impliment `IFakeAuthProfile` directly on your `HttpClient`:
You can also re-use any profiles that implement `IFakeAuthProfile` directly on your `HttpClient`:
```csharp
client.SetFakeAuthClaims<DefaultProfile>();
```
Expand All @@ -90,8 +90,8 @@ In .NET 6 you are no longer required to use a StartUp class. You can still use F
- For Demo based applications that you want people to download and run - without needing to set up a production identity service first, or without sharing your application id/client secret information.

### Not for - FakeAuth can not be used in production
- Do not use FakeAuth in a production enviroment
- FakeAuth will only work on http://localhost/ - it's intended to be a development tool.
- Do not use FakeAuth in a production environment
- FakeAuth will only work on http://localhost/ by default - it's intended to be a development tool.
- You will want to transition to an actual OAuth / Claims provider before you go to Production. Starting with Fake Auth can help you establish and document which claims your application will rely on.

## Contributing to FakeAuth
Expand Down
23 changes: 19 additions & 4 deletions Tests/FakeAuth.IntegrationTests/Manager_AccessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using FakeAuth.Testing;
using FakeAuth.Testing;

namespace FakeAuth.IntegrationTests
{
// Added Collection Attribute so that our tests aren't run in parallel
{
// Added Collection Attribute so that our tests aren't run in parallel
[Collection("Integration Tests")]
public class Manager_AccessTests :IDisposable
{
Expand Down Expand Up @@ -52,6 +52,21 @@ public async Task Should_Also_Be_Able_To_Access_Manager_Endpoint()
content.Should().NotBeNullOrEmpty();
}

[Fact]
public async Task Should_Be_Able_To_Access_Manager_Endpoint_Byhand_claims()
{
_client.DefaultRequestHeaders.Remove(FakeAuthDefaults.ClaimsHeaderName);
_client.DefaultRequestHeaders.Add(FakeAuthDefaults.ClaimsHeaderName, $"{ClaimTypes.Name},Joe Manager");
_client.DefaultRequestHeaders.Add(FakeAuthDefaults.ClaimsHeaderName, $"{ClaimTypes.Role},Manager");
// Act
var response = await _client.GetAsync("/api/protected");

// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().NotBeNullOrEmpty();
}

public void Dispose()
{
_client?.Dispose();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using FakeAuth.Testing;
using FluentAssertions;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using FluentAssertions;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace FakeAuth.IntegrationTests;

Expand All @@ -20,7 +20,7 @@ public Manager_AccessTests_with_Profiles()
_appUnderTest = new TestWebApplication();
_client = _appUnderTest.CreateClient();

_client.SetFakeAuthClaimns<ManagerJoeProfile>();
_client.SetFakeAuthClaims<ManagerJoeProfile>();
}


Expand Down Expand Up @@ -53,4 +53,4 @@ public void Dispose()
_client?.Dispose();
_appUnderTest?.Dispose();
}
}
}
45 changes: 45 additions & 0 deletions Tests/FakeAuth.IntegrationTests/NonLocalhostRejectionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System.Net;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;

namespace FakeAuth.IntegrationTests;

[Collection("Integration Tests")]
public sealed class NonLocalhostTests
{
[Theory]
[InlineData("localhost", HttpStatusCode.OK)]
[InlineData("example.com", HttpStatusCode.Unauthorized)]
public async Task ThrowsOnNonLocalhostByDefault(string host, HttpStatusCode expected)
{
using var app = new TestWebApplication
{
Host = host,
};
using var client = app.CreateClient();

var result = await client.GetAsync("/api/open");

result.StatusCode.Should().Be(expected);
}

[Theory]
[InlineData("example.com", HttpStatusCode.OK)]
[InlineData("foobar.com", HttpStatusCode.OK)]
[InlineData("localhost", HttpStatusCode.OK)]
[InlineData("google.com", HttpStatusCode.Unauthorized)]
public async Task AllowsNonLocalhostWhenConfigured(string host, HttpStatusCode expected)
{
using var app = new TestWebApplication
{
Host = host,
AllowedHosts = new[] { "example.com", "foobar.com", "localhost" },
};
using var client = app.CreateClient();

var result = await client.GetAsync("/api/open");

result.StatusCode.Should().Be(expected);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
using System.Threading.Tasks;
using System.Net;
using System.Security.Claims;
using System.Net.Http;
using FakeAuth.Testing;
using System.Net.Http;
using FakeAuth.Testing;

namespace FakeAuth.IntegrationTests
{
[Collection("Integration Tests")]
Expand All @@ -21,13 +21,13 @@ public Non_Manager_AccessTests_with_Profile()
_appUnderTest = new TestWebApplication();
_client = _appUnderTest.CreateClient();

_client.SetFakeAuthClaimns<NonManagerJoeProfile>();
_client.SetFakeAuthClaims<NonManagerJoeProfile>();
}
public void Dispose()
{
_client?.Dispose();
_appUnderTest?.Dispose();

public void Dispose()
{
_client?.Dispose();
_appUnderTest?.Dispose();
}

[Fact]
Expand Down
26 changes: 24 additions & 2 deletions Tests/FakeAuth.IntegrationTests/TestWebApplication.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
using System.Collections.Generic;
using System.Security.Claims;
using System.Collections.Immutable;
using System.Linq;
using intigrationtests.SampleWeb;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace FakeAuth.IntegrationTests
{
public class TestWebApplication : WebApplicationFactory<Program>
{
public string? Host { get; set; }
public IEnumerable<string> AllowedHosts { get; set; } = ImmutableArray<string>.Empty;

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);

builder.ConfigureServices(services =>
{
services.Configure<HostRewriteSettings>(s =>
{
s.Host = Host;
});
services.Configure<FakeAuthOptions>(FakeAuthDefaults.SchemaName, opts =>
{
opts.AllowedHosts = AllowedHosts.Any() ? AllowedHosts : new[] { FakeAuthOptions.DefaultAllowedHost };
});
});
}
}
}
6 changes: 6 additions & 0 deletions Tests/intigrationtests.SampleWeb/HostRewriteSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace intigrationtests.SampleWeb;

public sealed class HostRewriteSettings
{
public string Host { get; set; }
}
27 changes: 17 additions & 10 deletions Tests/intigrationtests.SampleWeb/Program.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using FakeAuth;
using intigrationtests.SampleWeb;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication()
.AddFakeAuth();
builder.Services.Configure<HostRewriteSettings>(_ => { });

builder.Services.AddAuthorization(options =>
{
Expand All @@ -20,9 +19,6 @@
.AddMicrosoftIdentityUI();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

//For(typeof(ILogger<>)).Use(typeof(Logger<>));


var app = builder.Build();

// Configure the HTTP request pipeline.
Expand All @@ -38,6 +34,17 @@

app.UseRouting();

app.Use((ctx, next) =>
{
var settings = app.Services.GetRequiredService<IOptions<HostRewriteSettings>>();

if (!string.IsNullOrEmpty(settings.Value.Host))
{
ctx.Request.Host = new HostString(settings.Value.Host);
}
return next();
});

app.UseAuthentication();
app.UseAuthorization();

Expand Down
2 changes: 1 addition & 1 deletion src/FakeAuth/FakeAuth.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>FakeAuth</RootNamespace>
<AssemblyName>FakeAuth</AssemblyName>
<Version>1.2.0</Version>
<Version>2.0.0</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>Caleb Jenkins</Authors>
<Company>Caleb Jenkins</Company>
Expand Down
18 changes: 10 additions & 8 deletions src/FakeAuth/FakeAuthHandler.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -29,23 +30,24 @@ ISystemClock clock
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
{
if (!CurrentUri.ToUpper().Contains("://LOCALHOST"))
var host = Context.Request.Host.Host;
if (!Options.AllowedHosts.Any(x => host.Equals(x, StringComparison.OrdinalIgnoreCase)))
{
_logger.LogError("Library only intended for localhost developement");
return AuthenticateResult.Fail("FakeAuth can only be used for localhost developement. Please impliment another OAuth solution for other scenarios");
var hostsString = string.Join(", ", Options.AllowedHosts);
_logger.LogError("Failing authentication due to unexpected host {Host} when allowed hosts is {AllowedHost}", host, hostsString);
return AuthenticateResult.Fail($"FakeAuth fails all requests that do not match {hostsString}; got host {host}.");
}

var claims = Options.Claims;
if (Request.Headers.ContainsKey(FakeAuthDefaults.ClaimsHeaderName))
{
var headerVal = Request.Headers[FakeAuthDefaults.ClaimsHeaderName][0];
using var stream = new MemoryStream(Convert.FromBase64String(headerVal));
using var reader = new BinaryReader(stream);
var claimValues = Request.Headers[FakeAuthDefaults.ClaimsHeaderName];

claims = new List<Claim>();
while (stream.Position < stream.Length)
foreach(var c in claimValues)
{
claims.Add(new Claim(reader));
var parts = c.Split(",");
claims.Add(new Claim(parts[0], parts[1]));
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/FakeAuth/FakeAuthOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ namespace FakeAuth
{
public class FakeAuthOptions : AuthenticationSchemeOptions
{
public const string DefaultAllowedHost = "localhost";
public FakeAuthOptions()
{
Claims = new List<Claim>();
}

public List<Claim> Claims { get; set; }

public IEnumerable<string> AllowedHosts { get; set; } = new[] { DefaultAllowedHost };
}
}
}
Loading