adjust server to use authentication where needed

This commit is contained in:
Stanley Dimant
2022-08-01 10:42:19 +02:00
parent cc53e5650d
commit 4d3226aa8b
5 changed files with 32 additions and 24 deletions

Submodule MareAPI updated: 714d990c0b...50a447c4d0

View File

@@ -7,6 +7,8 @@ using System.Text.Encodings.Web;
using System.Threading.Tasks;
using MareSynchronosServer.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -20,8 +22,13 @@ namespace MareSynchronosServer.Authentication
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
var endpoint = Context.GetEndpoint();
var endpointMetaData = endpoint?.Metadata?.GetMetadata<IAllowAnonymous>();
if (!Request.Headers.ContainsKey("Authorization") && endpointMetaData == null)
return AuthenticateResult.Fail("Failed Authorization");
else if (!Request.Headers.ContainsKey("Authorization") && endpointMetaData != null)
return AuthenticateResult.NoResult();
var authHeader = Request.Headers["Authorization"].ToString();
@@ -37,6 +44,10 @@ namespace MareSynchronosServer.Authentication
{
return AuthenticateResult.Fail("Failed Authorization");
}
else if (endpointMetaData != null && uid == null)
{
return AuthenticateResult.NoResult();
}
var claims = new List<Claim> {
new Claim(ClaimTypes.NameIdentifier, uid)

View File

@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using MareSynchronos.API;
using MareSynchronosServer.Authentication;
@@ -82,12 +79,6 @@ namespace MareSynchronosServer.Hubs
return otherEntries.Select(e => e.User.CharacterIdentification).Distinct().ToList();
}
[HubMethodName(Api.InvokeUserGetOnlineUsers)]
public async Task<int> GetOnlineUsers()
{
return await _dbContext.Users.CountAsync(u => !string.IsNullOrEmpty(u.CharacterIdentification));
}
[Authorize(AuthenticationSchemes = SecretKeyAuthenticationHandler.AuthScheme)]
[HubMethodName(Api.InvokeUserGetPairedClients)]
public async Task<List<ClientPairDto>> GetPairedClients()
@@ -139,7 +130,7 @@ namespace MareSynchronosServer.Hubs
MareMetrics.UserPushDataTo.Inc(visibleCharacterIds.Count);
}
[HubMethodName(Api.InvokeUserRegister)]
/*[HubMethodName(Api.InvokeUserRegister)]
public async Task<string> Register()
{
using var sha256 = SHA256.Create();
@@ -177,7 +168,7 @@ namespace MareSynchronosServer.Hubs
await _dbContext.SaveChangesAsync();
return computedHash;
}
}*/
[Authorize(AuthenticationSchemes = SecretKeyAuthenticationHandler.AuthScheme)]

View File

@@ -4,8 +4,10 @@ using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using MareSynchronos.API;
using MareSynchronosServer.Authentication;
using MareSynchronosServer.Data;
using MareSynchronosServer.Metrics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
@@ -14,6 +16,8 @@ using Microsoft.Extensions.Logging;
namespace MareSynchronosServer.Hubs
{
[AllowAnonymous]
[Authorize(AuthenticationSchemes = SecretKeyAuthenticationHandler.AuthScheme)]
public partial class MareHub : Hub
{
private readonly SystemInfoService _systemInfoService;
@@ -29,6 +33,7 @@ namespace MareSynchronosServer.Hubs
_dbContext = mareDbContext;
}
[AllowAnonymous]
[HubMethodName(Api.InvokeHeartbeat)]
public async Task<ConnectionDto> Heartbeat(string? characterIdentification)
{
@@ -44,7 +49,6 @@ namespace MareSynchronosServer.Hubs
if (!string.IsNullOrEmpty(userId) && !isBanned && !string.IsNullOrEmpty(characterIdentification))
{
_logger.LogInformation("Connection from " + userId);
var user = (await _dbContext.Users.SingleAsync(u => u.UID == userId));
if (!string.IsNullOrEmpty(user.CharacterIdentification) && characterIdentification != user.CharacterIdentification)
{
@@ -77,11 +81,13 @@ namespace MareSynchronosServer.Hubs
}
[HubMethodName(Api.InvokeGetSystemInfo)]
[AllowAnonymous]
public async Task<SystemInfoDto> GetSystemInfo()
{
return _systemInfoService.SystemInfoDto;
}
[AllowAnonymous]
public override Task OnConnectedAsync()
{
var feature = Context.Features.Get<IHttpConnectionFeature>();
@@ -90,6 +96,7 @@ namespace MareSynchronosServer.Hubs
return base.OnConnectedAsync();
}
[AllowAnonymous]
public override async Task OnDisconnectedAsync(Exception exception)
{
MareMetrics.Connections.Dec();

View File

@@ -15,8 +15,7 @@ using Microsoft.AspNetCore.SignalR;
using Prometheus;
using WebSocketOptions = Microsoft.AspNetCore.Builder.WebSocketOptions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.AspNetCore.Authorization;
namespace MareSynchronosServer
{
@@ -63,6 +62,7 @@ namespace MareSynchronosServer
options.DefaultScheme = SecretKeyAuthenticationHandler.AuthScheme;
})
.AddScheme<AuthenticationSchemeOptions, SecretKeyAuthenticationHandler>(SecretKeyAuthenticationHandler.AuthScheme, options => { });
services.AddAuthorization(options => options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -90,19 +90,18 @@ namespace MareSynchronosServer
KeepAliveInterval = TimeSpan.FromSeconds(10),
};
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Configuration["CacheDirectory"]),
RequestPath = "/cache",
ServeUnknownFileTypes = true
});
app.UseHttpMetrics();
app.UseWebSockets(webSocketOptions);
app.UseAuthentication();
app.UseAuthorization();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Configuration["CacheDirectory"]),
RequestPath = "/cache",
ServeUnknownFileTypes = true
});
app.UseEndpoints(endpoints =>
{