massive checkpoint

This commit is contained in:
2021-09-03 22:43:06 -05:00
parent bb1d2c491c
commit 2a3b7b32b4
40 changed files with 456 additions and 738 deletions

View File

@@ -6,17 +6,23 @@ using Gameboard.ShogiUI.Sockets.Repositories;
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket;
using Gameboard.ShogiUI.Sockets.Services;
using Gameboard.ShogiUI.Sockets.Services.RequestValidators;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
@@ -34,29 +40,16 @@ namespace Gameboard.ShogiUI.Sockets
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Socket ActionHandlers
services.AddSingleton<ICreateGameHandler, CreateGameHandler>();
services.AddSingleton<IJoinByCodeHandler, JoinByCodeHandler>();
services.AddSingleton<IJoinGameHandler, JoinGameHandler>();
services.AddSingleton<IListGamesHandler, ListGamesHandler>();
services.AddSingleton<ILoadGameHandler, LoadGameHandler>();
services.AddSingleton<IMoveHandler, MoveHandler>();
// Managers
services.AddSingleton<ISocketConnectionManager, SocketConnectionManager>();
services.AddSingleton<ISocketTokenManager, SocketTokenManager>();
services.AddSingleton<ISocketTokenCache, SocketTokenCache>();
services.AddSingleton<IGameboardManager, GameboardManager>();
// Services
services.AddSingleton<IValidator<CreateGameRequest>, CreateGameRequestValidator>();
services.AddSingleton<IValidator<JoinByCodeRequest>, JoinByCodeRequestValidator>();
services.AddSingleton<IValidator<JoinGameRequest>, JoinGameRequestValidator>();
services.AddSingleton<IValidator<ListGamesRequest>, ListGamesRequestValidator>();
services.AddSingleton<IValidator<LoadGameRequest>, LoadGameRequestValidator>();
services.AddSingleton<IValidator<MoveRequest>, MoveRequestValidator>();
services.AddSingleton<ISocketService, SocketService>();
// Repositories
services.AddTransient<IGameboardRepository, GameboardRepository>();
services.AddSingleton<IClaimsTransformation, ShogiUserClaimsTransformer>();
services.AddHttpClient("couchdb", c =>
{
var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:admin"));
@@ -66,37 +59,56 @@ namespace Gameboard.ShogiUI.Sockets
var baseUrl = $"{Configuration["AppSettings:CouchDB:Url"]}/{Configuration["AppSettings:CouchDB:Database"]}/";
c.BaseAddress = new Uri(baseUrl);
});
services.AddTransient<IGameboardRepository, GameboardRepository>();
//services.AddSingleton<IAuthenticatedHttpClient, AuthenticatedHttpClient>();
//services.AddSingleton<ICouchClient>(provider => new CouchClient(databaseName, couchUrl));
services.AddControllers();
services
.AddAuthentication(options =>
.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Formatting = Formatting.Indented;
options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0";
options.Audience = "935df672-efa6-45fa-b2e8-b76dfd65a122";
options.TokenValidationParameters.ValidateIssuer = true;
options.TokenValidationParameters.ValidateAudience = true;
NamingStrategy = new CamelCaseNamingStrategy { ProcessDictionaryKeys = true }
};
options.SerializerSettings.Converters = new[] { new StringEnumConverter() };
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
options.Events = new JwtBearerEvents
{
OnMessageReceived = (context) =>
{
if (context.HttpContext.WebSockets.IsWebSocketRequest)
{
Console.WriteLine("Yep");
}
return Task.FromResult(0);
}
};
});
services.AddAuthentication("CookieOrJwt")
.AddPolicyScheme("CookieOrJwt", "Either cookie or jwt", options =>
{
options.ForwardDefaultSelector = context =>
{
var bearerAuth = context.Request.Headers["Authorization"].FirstOrDefault()?.StartsWith("Bearer ") ?? false;
return bearerAuth
? JwtBearerDefaults.AuthenticationScheme
: CookieAuthenticationDefaults.AuthenticationScheme;
};
})
.AddCookie(options =>
{
options.Cookie.Name = "session-id";
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
options.SlidingExpiration = true;
})
.AddMicrosoftIdentityWebApi(Configuration);
services.AddSwaggerDocument(config =>
{
config.AddSecurity("Bearer", new NSwag.OpenApiSecurityScheme
{
Type = NSwag.OpenApiSecuritySchemeType.OAuth2,
Flow = NSwag.OpenApiOAuth2Flow.AccessCode,
AuthorizationUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
TokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
Scopes = new Dictionary<string, string> { { "api://c1e94676-cab0-42ba-8b6c-9532b8486fff/access_as_user", "The scope" } },
Scheme = "Bearer"
});
config.PostProcess = document =>
{
document.Info.Title = "Gameboard.ShogiUI.Sockets";
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -114,30 +126,45 @@ namespace Gameboard.ShogiUI.Sockets
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
var client = PublicClientApplicationBuilder
.Create(Configuration["AzureAd:ClientId"])
.WithLogging(
(level, message, pii) =>
{
},
LogLevel.Verbose,
true,
true
)
.Build();
}
else
{
app.UseHsts();
}
app
.UseRequestResponseLogging()
.UseCors(
opt => opt
.WithOrigins(origins)
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Set-Cookie")
.AllowCredentials()
)
.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseWebSockets(socketOptions)
.UseEndpoints(endpoints =>
.UseRequestResponseLogging()
.UseCors(opt => opt.WithOrigins(origins).AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("Set-Cookie").AllowCredentials())
.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseOpenApi()
.UseSwaggerUi3(config =>
{
config.OAuth2Client = new NSwag.AspNetCore.OAuth2ClientSettings()
{
endpoints.MapControllers();
})
.Use(async (context, next) =>
ClientId = "c1e94676-cab0-42ba-8b6c-9532b8486fff",
UsePkceWithAuthorizationCodeGrant = true
};
//config.WithCredentials = true;
})
.UseWebSockets(socketOptions)
.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
})
.Use(async (context, next) =>
{
if (context.WebSockets.IsWebSocketRequest)
{