diff --git a/src/Money.Api/Domain/Hubs/ApiHub.cs b/src/Money.Api/Domain/Hubs/ApiHub.cs index 9197a6b4..dbd15953 100644 --- a/src/Money.Api/Domain/Hubs/ApiHub.cs +++ b/src/Money.Api/Domain/Hubs/ApiHub.cs @@ -49,6 +49,9 @@ public ApiHub(IEventHandlerCollection eventHandlers, FormatterContainer formatte { string connectionId = Context.ConnectionId; string userId = Context.User.FindFirstValue(ClaimTypes.NameIdentifier); + if (userId == null) + throw new UnauthorizedAccessException(); + IKey userKey = StringKey.Create(userId, "User"); return (connectionId, userKey); } diff --git a/src/Money.Api/Startup.cs b/src/Money.Api/Startup.cs index 08fd98bb..bf4a40d4 100644 --- a/src/Money.Api/Startup.cs +++ b/src/Money.Api/Startup.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -65,6 +66,22 @@ public void ConfigureServices(IServiceCollection services) IssuerSigningKey = configuration.GetSecurityKey() }; + options.Events = new JwtBearerEvents + { + OnMessageReceived = context => + { + var path = context.HttpContext.Request.Path; + if (path.StartsWithSegments("/api")) + { + var accessToken = context.HttpContext.Request.Query["access_token"]; + if (!string.IsNullOrEmpty(accessToken)) + context.Token = accessToken; + } + + return Task.CompletedTask; + } + }; + options.SaveToken = true; }); @@ -75,7 +92,7 @@ public void ConfigureServices(IServiceCollection services) .RequireAuthenticatedUser() .Build(); }); - + services .AddIdentityCore(options => Configuration.GetSection("Identity").GetSection("Password").Bind(options.Password)) .AddEntityFrameworkStores(); @@ -93,6 +110,7 @@ public void ConfigureServices(IServiceCollection services) services .AddSingleton() + .AddSingleton(new DefaultUserIdProvider()) .AddSingleton() .AddSingleton() .AddSingleton(); @@ -108,12 +126,22 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env) else app.UseStatusCodePages(); + app.UseCors(p => + { + p.WithOrigins("http://localhost:48613"); + p.AllowAnyMethod(); + p.AllowCredentials(); + p.AllowAnyHeader(); + p.SetPreflightMaxAge(TimeSpan.FromMinutes(10)); + }); + + app.UseAuthentication(); + app.UseSignalR(routes => { routes.MapHub("/api"); }); - app.UseAuthentication(); app.UseMvc(); } }