Skip to content

Commit

Permalink
#218 - Setup CORS.
Browse files Browse the repository at this point in the history
  • Loading branch information
maraf committed Mar 2, 2019
1 parent 8162ba2 commit adf7cd2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/Money.Api/Domain/Hubs/ApiHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
32 changes: 30 additions & 2 deletions src/Money.Api/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
});

Expand All @@ -75,7 +92,7 @@ public void ConfigureServices(IServiceCollection services)
.RequireAuthenticatedUser()
.Build();
});

services
.AddIdentityCore<ApplicationUser>(options => Configuration.GetSection("Identity").GetSection("Password").Bind(options.Password))
.AddEntityFrameworkStores<ApplicationDbContext>();
Expand All @@ -93,6 +110,7 @@ public void ConfigureServices(IServiceCollection services)

services
.AddSingleton<IHttpContextAccessor, HttpContextAccessor>()
.AddSingleton<IUserIdProvider>(new DefaultUserIdProvider())
.AddSingleton<ApiHub>()
.AddSingleton<CommandMapper>()
.AddSingleton<QueryMapper>();
Expand All @@ -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<ApiHub>("/api");
});

app.UseAuthentication();
app.UseMvc();
}
}
Expand Down

0 comments on commit adf7cd2

Please sign in to comment.