199 lines
7.4 KiB
C#
199 lines
7.4 KiB
C#
using System.Text;
|
|
using BlueWest.Cryptography;
|
|
using BlueWest.Data.Application.Users;
|
|
using BlueWest.Data.Auth;
|
|
using BlueWest.Data.Auth.Context.Users;
|
|
using CodeLiturgy.Domain;
|
|
using BlueWest.WebApi.Context.Users;
|
|
using CodeLiturgy.Views.Utils;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace CodeLiturgy.Views;
|
|
|
|
public static class StartupExtensions
|
|
{
|
|
/*
|
|
private static MySqlServerVersion GetMySqlServerVersion(int major, int minor, int build) =>
|
|
new(new Version(major, minor, build));
|
|
*/
|
|
|
|
private static string GetConnectionString(this IConfiguration configurationRoot, string db)
|
|
{
|
|
var startupMode = configurationRoot["mode"];
|
|
|
|
if (!string.IsNullOrEmpty(startupMode) && startupMode == "docker")
|
|
{
|
|
var config = configurationRoot.GetSection("ConnectionStringDocker")[db];
|
|
return config;
|
|
}
|
|
else
|
|
{
|
|
return configurationRoot.GetSection("ConnectionStringNoDocker")[db] ?? string.Empty;
|
|
}
|
|
}
|
|
|
|
|
|
private static bool IsDockerMode(this IConfiguration config)
|
|
{
|
|
var startupMode = config["mode"];
|
|
return startupMode == "docker";
|
|
}
|
|
|
|
internal static IServiceCollection AddAuthServerServices(this IServiceCollection services,
|
|
IConfiguration configuration, IWebHostEnvironment environment)
|
|
{
|
|
services.AddSession(options =>
|
|
{
|
|
options.Cookie.Domain = SessionConstants.CookieDomain;
|
|
options.Cookie.HttpOnly = true;
|
|
options.IdleTimeout = TimeSpan.FromHours(8);
|
|
});
|
|
|
|
services
|
|
.AddScoped<IJwtTokenHandler, JwtTokenHandler>()
|
|
.AddScoped<IJwtFactory, JwtFactory>()
|
|
.AddScoped<UserRepository>()
|
|
.AddScoped<IUserManager, ApplicationUserManager>()
|
|
.AddScoped<IAuthManager, AuthManager>()
|
|
.AddScoped<IHasher, Hasher>();
|
|
|
|
// Database Context and Swagger
|
|
|
|
|
|
// Register the ConfigurationBuilder instance of AuthSettings
|
|
var authSettings = configuration.GetSection(nameof(AuthSettings));
|
|
services.Configure<AuthSettings>(authSettings);
|
|
var signingKey = new SymmetricSecurityKey
|
|
(Encoding.ASCII.GetBytes(authSettings[nameof(AuthSettings.SecretKey)]));
|
|
|
|
// jwt wire up
|
|
// Get options from app settings
|
|
var jwtAppSettingOptions = configuration
|
|
.GetSection(nameof(JwtIssuerOptions));
|
|
|
|
// Configure JwtIssuerOptions
|
|
services.Configure<JwtIssuerOptions>(options =>
|
|
{
|
|
options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
|
|
options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
|
|
options.SigningCredentials = new SigningCredentials
|
|
(signingKey, SecurityAlgorithms.HmacSha256);
|
|
});
|
|
|
|
var tokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = true,
|
|
ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
|
|
|
|
ValidateAudience = true,
|
|
ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
|
|
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = signingKey,
|
|
|
|
RequireExpirationTime = false,
|
|
ValidateLifetime = true,
|
|
ClockSkew = TimeSpan.Zero
|
|
};
|
|
|
|
services.AddAuthentication(options =>
|
|
{
|
|
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
})
|
|
.AddCookie(options =>
|
|
{
|
|
options.LoginPath = Routes.AuthLoginRoute;
|
|
options.LogoutPath = Routes.AuthLogoutRoute;
|
|
})
|
|
.AddJwtBearer(configureOptions =>
|
|
{
|
|
configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
|
|
configureOptions.TokenValidationParameters = tokenValidationParameters;
|
|
configureOptions.SaveToken = true;
|
|
configureOptions.Events = new JwtBearerEvents
|
|
{
|
|
OnAuthenticationFailed = context =>
|
|
{
|
|
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
|
|
{
|
|
context.Response.Headers.Add("Token-Expired", "true");
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
},
|
|
};
|
|
});
|
|
|
|
|
|
// api user claim policy
|
|
services.AddAuthorization(options =>
|
|
{
|
|
options.AddPolicy(SessionConstants.ApiNamePolicy,
|
|
policy => policy.RequireClaim(Constants.JwtClaimIdentifiers.Rol,
|
|
Constants.JwtClaims.ApiAccess));
|
|
options.AddPolicy(SessionConstants.CookieNamePolicy, policy =>
|
|
{
|
|
policy.RequireClaim(Constants.CookieClaims.CookieAccess);
|
|
});
|
|
});
|
|
|
|
// add identity
|
|
var identityBuilder = services.AddIdentityCore<ApplicationUser>(o =>
|
|
{
|
|
o.User.RequireUniqueEmail = true;
|
|
|
|
// configure identity options
|
|
o.Password.RequireDigit = false;
|
|
o.Password.RequireLowercase = false;
|
|
o.Password.RequireUppercase = false;
|
|
o.Password.RequireNonAlphanumeric = false;
|
|
o.Password.RequiredLength = 6;
|
|
})
|
|
.AddUserManager<ApplicationUserManager>()
|
|
.AddUserStore<UserRepository>();
|
|
|
|
identityBuilder =
|
|
new IdentityBuilder(identityBuilder.UserType, typeof(ApplicationRole), identityBuilder.Services);
|
|
identityBuilder
|
|
.AddEntityFrameworkStores<ApplicationUserDbContext>()
|
|
.AddDefaultTokenProviders();
|
|
|
|
return services;
|
|
}
|
|
|
|
|
|
private static DbContextOptionsBuilder UsePsqlConfiguration(this DbContextOptionsBuilder builder, IConfiguration configuration)
|
|
{
|
|
var connString = configuration.GetConnectionString("database");
|
|
builder.UseNpgsql(connString);
|
|
return builder;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Setup database Contexts
|
|
/// </summary>
|
|
/// <param name="serviceCollection"></param>
|
|
/// <param name="configuration"></param>
|
|
/// <param name="environment"></param>
|
|
/// <returns></returns>
|
|
public static IServiceCollection PreparePostgresqlDatabasePool(this IServiceCollection serviceCollection,
|
|
IConfiguration configuration, IWebHostEnvironment environment)
|
|
{
|
|
return serviceCollection
|
|
.AddDbContextPool<SiteDbContext>(options => options.UsePsqlConfiguration(configuration))
|
|
.AddDbContextPool<CountryDbContext>(options => options.UsePsqlConfiguration(configuration))
|
|
.AddDbContextPool<ApplicationUserDbContext>(options =>
|
|
options.UsePsqlConfiguration(configuration));
|
|
}
|
|
|
|
|
|
} |