Skip to content

Commit

Permalink
Move AppHost init to Program.cs
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Feb 8, 2022
1 parent 58efbff commit 0e3d9d6
Show file tree
Hide file tree
Showing 4 changed files with 131 additions and 120 deletions.
123 changes: 6 additions & 117 deletions MyApp/Configure.AppHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,138 +2,24 @@
using MyApp.Data;
using MyApp.Models;
using MyApp.Services;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.EntityFrameworkCore;
using MyApp.ServiceInterface;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;

[assembly: HostingStartup(typeof(MyApp.AppHost))]

namespace MyApp;

/// <summary>
/// To create Identity SQL Server database, change "ConnectionStrings" in appsettings.json
/// $ dotnet ef migrations add CreateMyAppIdentitySchema
/// $ dotnet ef database update
/// </summary>
public class AppHost : AppHostBase, IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder
.ConfigureServices((context,services) => {
var config = context.Configuration;
#if DEBUG
services.AddMvc(options => options.EnableEndpointRouting = false).AddRazorRuntimeCompilation();
#else
services.AddMvc(options => options.EnableEndpointRouting = false);
#endif

services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(config.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>(options => {
options.User.AllowedUserNameCharacters = null;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.AddAuthentication(IISDefaults.AuthenticationScheme)
.AddTwitter(options => { /* Create Twitter App at: https://dev.twitter.com/apps */
options.ConsumerKey = config["oauth.twitter.ConsumerKey"];
options.ConsumerSecret = config["oauth.twitter.ConsumerSecret"];
options.SaveTokens = true;
options.RetrieveUserDetails = true;
})
.AddFacebook(options => { /* Create App https://developers.facebook.com/apps */
options.AppId = config["oauth.facebook.AppId"];
options.AppSecret = config["oauth.facebook.AppSecret"];
options.SaveTokens = true;
options.Scope.Clear();
config.GetSection("oauth.facebook.Permissions").GetChildren()
.Each(x => options.Scope.Add(x.Value));
})
.AddGoogle(options => { /* Create App https://console.developers.google.com/apis/credentials */
options.ClientId = config["oauth.google.ConsumerKey"];
options.ClientSecret = config["oauth.google.ConsumerSecret"];
options.SaveTokens = true;
})
.AddMicrosoftAccount(options => { /* Create App https://apps.dev.microsoft.com */
options.ClientId = config["oauth.microsoftgraph.AppId"];
options.ClientSecret = config["oauth.microsoftgraph.AppSecret"];
options.SaveTokens = true;
});

services.Configure<ForwardedHeadersOptions>(options => {
//https://github.com/aspnet/IISIntegration/issues/140#issuecomment-215135928
options.ForwardedHeaders = ForwardedHeaders.XForwardedProto;
});

services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;

// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;

// User settings
options.User.RequireUniqueEmail = true;
// Configure ASP.NET Core IOC Dependencies
});

services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromDays(150);
// If the LoginPath isn't set, ASP.NET Core defaults
// the path to /Account/Login.
options.LoginPath = "/Account/Login";
// If the AccessDeniedPath isn't set, ASP.NET Core defaults
// the path to /Account/AccessDenied.
options.AccessDeniedPath = "/Account/AccessDenied";
options.SlidingExpiration = true;
});

// Add application services.
services.AddTransient<IEmailSender, EmailSender>();

// Populate ApplicationUser with Auth Info
services.AddTransient<IExternalLoginAuthInfoProvider>(c =>
new ExternalLoginAuthInfoProvider(config));
})
.Configure(app => {
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();

app.UseServiceStack(new AppHost());

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

AddSeedUsers(app).Wait();
});

public AppHost() : base("MyApp", typeof(MyServices).Assembly) { }

// Configure your AppHost with the necessary configuration and dependencies your App needs
Expand Down Expand Up @@ -170,6 +56,9 @@ public override void Configure(Container container)
}
},
}));


AddSeedUsers(base.App).Wait();
}

private async Task AddSeedUsers(IApplicationBuilder app)
Expand Down
4 changes: 3 additions & 1 deletion MyApp/Models/ApplicationUser.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
Expand Down
4 changes: 3 additions & 1 deletion MyApp/MyApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup>
<Using Include="MyApp" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="ServiceStack" Version="6.*" />
Expand Down
120 changes: 119 additions & 1 deletion MyApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,110 @@
var builder = WebApplication.CreateBuilder(args);
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.EntityFrameworkCore;
using ServiceStack;
using MyApp.Data;
using MyApp.Models;
using MyApp.Services;

var builder = WebApplication.CreateBuilder(args);

var config = builder.Configuration;
var services = builder.Services;
#if DEBUG
services.AddMvc(options => options.EnableEndpointRouting = false).AddRazorRuntimeCompilation();
#else
services.AddMvc(options => options.EnableEndpointRouting = false);
#endif

services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

// To create Identity SQL Server database, change "ConnectionStrings" in appsettings.json
// $ dotnet ef migrations add CreateMyAppIdentitySchema
// $ dotnet ef database update
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(config.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>(options => {
options.User.AllowedUserNameCharacters = null;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.AddAuthentication(IISDefaults.AuthenticationScheme)
.AddTwitter(options => { /* Create Twitter App at: https://dev.twitter.com/apps */
options.ConsumerKey = config["oauth.twitter.ConsumerKey"];
options.ConsumerSecret = config["oauth.twitter.ConsumerSecret"];
options.SaveTokens = true;
options.RetrieveUserDetails = true;
})
.AddFacebook(options => { /* Create App https://developers.facebook.com/apps */
options.AppId = config["oauth.facebook.AppId"];
options.AppSecret = config["oauth.facebook.AppSecret"];
options.SaveTokens = true;
options.Scope.Clear();
config.GetSection("oauth.facebook.Permissions").GetChildren()
.Each(x => options.Scope.Add(x.Value));
})
.AddGoogle(options => { /* Create App https://console.developers.google.com/apis/credentials */
options.ClientId = config["oauth.google.ConsumerKey"];
options.ClientSecret = config["oauth.google.ConsumerSecret"];
options.SaveTokens = true;
})
.AddMicrosoftAccount(options => { /* Create App https://apps.dev.microsoft.com */
options.ClientId = config["oauth.microsoftgraph.AppId"];
options.ClientSecret = config["oauth.microsoftgraph.AppSecret"];
options.SaveTokens = true;
});

services.Configure<ForwardedHeadersOptions>(options => {
//https://github.com/aspnet/IISIntegration/issues/140#issuecomment-215135928
options.ForwardedHeaders = ForwardedHeaders.XForwardedProto;
});

services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;

// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;

// User settings
options.User.RequireUniqueEmail = true;
});

services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromDays(150);
// If the LoginPath isn't set, ASP.NET Core defaults
// the path to /Account/Login.
options.LoginPath = "/Account/Login";
// If the AccessDeniedPath isn't set, ASP.NET Core defaults
// the path to /Account/AccessDenied.
options.AccessDeniedPath = "/Account/AccessDenied";
options.SlidingExpiration = true;
});

// Add application services.
services.AddTransient<IEmailSender, EmailSender>();

// Populate ApplicationUser with Auth Info
services.AddTransient<IExternalLoginAuthInfoProvider>(c =>
new ExternalLoginAuthInfoProvider(config));

var app = builder.Build();

Expand All @@ -14,5 +120,17 @@
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();

app.UseServiceStack(new AppHost());

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

app.Run();

0 comments on commit 0e3d9d6

Please sign in to comment.