Skip to content

Serilog example fixed #1

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

Open
wants to merge 3 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
15 changes: 6 additions & 9 deletions Sample.Authentication/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;

namespace Sample.Authentication
{
public class Program
{

public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
Expand All @@ -31,8 +25,11 @@ public static IWebHost BuildWebHost(string[] args) =>

WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((b)=> {
b.AddSerilog(Log.Logger); // this does!
})
.UseUrls("http://*:5000", "http://*:5001", "http://*:5002", "http://*:5003", "http://*:5004")
.UseSerilog()
// .UseSerilog(providers: Providers) // this doesn't work with dotnettency!
.Build();
}
}
11 changes: 6 additions & 5 deletions Sample.Authentication/Sample.Authentication.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
Expand All @@ -9,11 +9,12 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Dotnettency.AspNetCore.Container" Version="2.0.0-unstable.112" />
<PackageReference Include="Dotnettency.AspNetCore.MiddlewarePipeline" Version="2.0.0-unstable.112" />
<PackageReference Include="Dotnettency.Container.Autofac" Version="2.0.0-unstable.112" />


<PackageReference Include="Dotnettency.AspNetCore" Version="2.0.0-alpha.139" />
<PackageReference Include="Dotnettency.Container.Autofac" Version="2.0.0-alpha.139" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
<PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.0-dev-10240" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
</ItemGroup>

Expand Down
162 changes: 89 additions & 73 deletions Sample.Authentication/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Security.Claims;
Expand All @@ -15,90 +16,105 @@ public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
IServiceProvider serviceProvider = services.AddAspNetCoreMultiTenancy<Tenant>((options) =>
var defaultServices = services.Clone();

try
{
options
.InitialiseTenant<TenantShellFactory>() // factory class to load tenant when it needs to be initialised for the first time. Can use overload to provide a delegate instead.
.ConfigureTenantContainers((containerBuilder) =>
{
containerBuilder.WithAutofac((tenant, tenantServices) =>
{
if (tenant.Name == "Moogle")
{
tenantServices.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie((c) =>
{
c.Cookie.Name = tenant.Name;
});
}
})
.AddPerRequestContainerMiddlewareServices() // services needed for per tenant container middleware.
.AddPerTenantMiddlewarePipelineServices(); // services needed for per tenant middleware pipeline.
})
.ConfigureTenantMiddleware((a) =>
{
a.OnInitialiseTenantPipeline((b, c) =>
{
c.UseDeveloperExceptionPage();
c.UseStaticFiles();

// var log = c.ApplicationServices.GetRequiredService<ILogger<Startup>>();
if (b.Tenant.Name == "Moogle")
{
c.UseAuthentication();

// Browse to /Protected endpoint, will issue a challenge if not authenticated.
// This challenge automatically redirects to the default login path = /Account/Login
c.Map("/Protected", (d) =>
{
d.Run(async (h) =>
{
if (!h.User.Identity?.IsAuthenticated ?? false)
{
await h.ChallengeAsync();
}
else
{
await h.Response.WriteAsync("Authenticated as: " + h.User.FindFirstValue(ClaimTypes.Name));
}
});
});

// Browse to /Account/Login will automatically create a sign in cookie then redirect to /Protected
c.Map("/Account/Login", (d) =>
{
d.Run(async (h) =>
{
List<Claim> claims = new List<Claim>{
var sp = services.AddMultiTenancy<Tenant>((builder) =>
{
builder.IdentifyTenantsWithRequestAuthorityUri()
.InitialiseTenant<TenantShellFactory>()
.AddAspNetCore()
.ConfigureTenantContainers((containerOptions) =>
{
containerOptions
.SetDefaultServices(defaultServices)
.Autofac((tenant, tenantServices) =>
{
if (tenant.Name == "Moogle")
{
tenantServices.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie((c) =>
{
c.Cookie.Name = tenant.Name;
});
}
});
})
.ConfigureTenantMiddleware((tenantOptions) =>
{
tenantOptions.AspNetCorePipeline((context, tenantAppBuilder) =>
{

tenantAppBuilder.UseDeveloperExceptionPage();
tenantAppBuilder.UseStaticFiles();

// var log = c.ApplicationServices.GetRequiredService<ILogger<Startup>>();
if (context.Tenant.Name == "Moogle")
{
tenantAppBuilder.UseAuthentication();

// Browse to /Protected endpoint, will issue a challenge if not authenticated.
// This challenge automatically redirects to the default login path = /Account/Login
tenantAppBuilder.Map("/Protected", (d) =>
{
d.Run(async (h) =>
{
if (!h.User.Identity?.IsAuthenticated ?? false)
{
await h.ChallengeAsync();
}
else
{
await h.Response.WriteAsync("Authenticated as: " + h.User.FindFirstValue(ClaimTypes.Name));
}
});
});

// Browse to /Account/Login will automatically create a sign in cookie then redirect to /Protected
tenantAppBuilder.Map("/Account/Login", (d) =>
{
d.Run(async (h) =>
{
List<Claim> claims = new List<Claim>{
new Claim(ClaimTypes.Name, "testuser"),
new Claim("FullName", "test user"),
new Claim(ClaimTypes.Role, "Administrator"),
};
};

ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

AuthenticationProperties authProperties = new AuthenticationProperties
{
RedirectUri = "/Protected"
};
AuthenticationProperties authProperties = new AuthenticationProperties
{
RedirectUri = "/Protected"
};

await h.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity), authProperties);
});
});
await h.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity), authProperties);
});
});

}
}

// All tenants have welcome page middleware enabled.
c.UseWelcomePage();
// All tenants have welcome page middleware enabled.
tenantAppBuilder.UseWelcomePage();

});
});
});
});

});
});
return sp;

}
catch (Exception ex)
{

throw ex;
}

// When using tenant containers, must return IServiceProvider.
return serviceProvider;
// Note: in asp.netcore 3.0.0 we don't need to, but something additional must be registered in program createhostbuilder.

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand All @@ -111,8 +127,8 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)

app = app.UseMultitenancy<Tenant>((options) =>
{
options.UsePerTenantContainers();
options.UsePerTenantMiddlewarePipeline();
options.UseTenantContainers();
options.UsePerTenantMiddlewarePipeline(app);
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sample.Authentication/TenantShellFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Sample.Authentication
{
public class TenantShellFactory : ITenantShellFactory<Tenant>
{
public Task<TenantShell<Tenant>> Get(TenantDistinguisher distinguisher)
public Task<TenantShell<Tenant>> Get(TenantIdentifier distinguisher)
{
if (distinguisher.Uri.Port == 5000 || distinguisher.Uri.Port == 5001)
{
Expand Down