Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions UbikLink.AppHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
var authTokenStoreKey = builder.AddParameter("auth-token-store-key", secret: true);
var authRegisterAuthorizationKey = builder.AddParameter("auth-register-authorization-key", secret: true);
var emailActivationEnable = builder.AddParameter("email-activation-enable", secret: false);
var hubSignSecureKey = builder.AddParameter("hub-signtoken-key", secret: true);

//Postgres (local)
var db = builder.AddPostgres("ubiklink-postgres", postgresUsername, postgresPassword)
Expand Down Expand Up @@ -56,12 +57,21 @@
.WithEnvironment("Messaging__RabbitUser", rabbitUser)
.WithEnvironment("Messaging__RabbitPassword", rabbitPassword)
.WithEnvironment("AuthRegister__Key", authRegisterAuthorizationKey)
.WithEnvironment("AuthRegister__HubSignSecureKey", hubSignSecureKey)
.WithEnvironment("AuthRegister__EmailActivationActivated", emailActivationEnable)
.WithReference(securityDB)
.WaitFor(securityDB)
.WithReference(rabbitmq)
.WithReference(serviceBus);

//Hub
var hub = builder.AddProject<Projects.UbikLink_Commander>("ubiklink-commander")
.WithEnvironment("AuthRegister__HubSignSecureKey", hubSignSecureKey)
.WithReference(securityDB)
.WaitFor(securityDB)
.WithReference(rabbitmq)
.WithReference(serviceBus);

//Proxy
var proxy = builder.AddProject<Projects.UbikLink_Proxy>("ubiklink-proxy")
.WithEnvironment("Proxy__Token",securitytoken)
Expand All @@ -76,8 +86,10 @@
.WithReference(cache)
.WithReference(serviceBus)
.WithReference(rabbitmq)
.WithReference(hub)
.WaitFor(cache)
.WaitFor(securityApi)
.WaitFor(hub)
.WaitFor(keycloak);

//.WithReference(rabbitmq)
Expand Down Expand Up @@ -105,6 +117,7 @@
.WithEnvironment("Messaging__RabbitUser", rabbitUser)
.WithEnvironment("Messaging__RabbitPassword", rabbitPassword);


//Add npm sevltekit project (not work with fnm.... because of path)
//builder.AddNpmApp("svelte-ui", "../svelte-link-ui","dev")
// .WithEnvironment("BROWSER", "none")
Expand Down
1 change: 1 addition & 0 deletions UbikLink.AppHost/UbikLink.AppHost.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\UbikLink.Commander\UbikLink.Commander.csproj" />
<ProjectReference Include="..\UbikLink.Proxy\UbikLink.Proxy.csproj" />
<ProjectReference Include="..\UbikLink.Security.Api\UbikLink.Security.Api.csproj" />
<ProjectReference Include="..\UbikLink.Security.UI\UbikLink.Security.UI.csproj" />
Expand Down
3 changes: 2 additions & 1 deletion UbikLink.AppHost/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,6 @@
"Parameters:keycloak-password": "admin",
"Parameters:auth-token-store-key": "Ye6Y36ocA4SaGqYzd0HgmqMhVaM2jlkE",
"Parameters:auth-register-authorization-key": "Ye6Y36oddddcA4SaGqYzd0HgmqMhVaM2jlkE",
"Parameters:email-activation-enable": "false"
"Parameters:email-activation-enable": "false",
"Parameters:hub-signtoken-key": "0YksXysNolWIH4K0dRzhZm/pv/q+TDVUujmCIsm/nlI="
}
89 changes: 89 additions & 0 deletions UbikLink.Commander/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using UbikLink.Commander.Test;
using UbikLink.Common.Api;
using UbikLink.Common.Auth;

//var SecurityKey = new SymmetricSecurityKey(RandomNumberGenerator.GetBytes(32));

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();

// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
//builder.Services.AddOpenApi();
builder.Services.AddSignalR();
builder.Services.AddCors();

var keys = new AuthRegisterAuthKey();
builder.Configuration.GetSection(AuthRegisterAuthKey.Position).Bind(keys);
var SecurityKey = new SymmetricSecurityKey(Convert.FromBase64String(keys.HubSignSecureKey));


builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
LifetimeValidator = (before, expires, token, parameters) => expires > DateTime.UtcNow,
ValidateAudience = false,
ValidateIssuer = false,
ValidateActor = false,
ValidateLifetime = true,
IssuerSigningKey = SecurityKey
};

options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];

if (!string.IsNullOrEmpty(accessToken))
{
context.Token = context.Request.Query["access_token"];
}
return Task.CompletedTask;
}
};
});

builder.Services.AddAuthorizationBuilder()
.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireClaim(ClaimTypes.NameIdentifier);
policy.RequireClaim(ClaimTypes.UserData);
});


var app = builder.Build();

app.MapDefaultEndpoints();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
//app.MapOpenApi();
}

app.UseAuthentication();
app.UseAuthorization();

app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());

app.MapHub<ChatHub>("/chat");

//app.UseHttpsRedirection();


app.Run();
23 changes: 23 additions & 0 deletions UbikLink.Commander/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5122",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7036;http://localhost:5122",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
40 changes: 40 additions & 0 deletions UbikLink.Commander/Test/ChatHub.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;

namespace UbikLink.Commander.Test
{
[Authorize]
public class ChatHub : Hub<IChatClient>
{
public override Task OnConnectedAsync()
{
var userId = Context.User?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
var tenantId = Context.User?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.UserData)?.Value;

if (userId == null || tenantId == null)
{
Context.Abort();
return Task.CompletedTask;
}

return base.OnConnectedAsync();
}

public override Task OnDisconnectedAsync(Exception? exception)
{
return base.OnDisconnectedAsync(exception);
}

public async Task SendMessage(string user, string message)
{
await Clients.All.ReceiveMessage(user,message);
}
}

public interface IChatClient
{
Task ReceiveMessage(string user, string message);
}
}
24 changes: 24 additions & 0 deletions UbikLink.Commander/UbikLink.Commander.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.2" />
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\UbikLink.Common\UbikLink.Common.csproj" />
<ProjectReference Include="..\UbikLink.ServiceDefaults\UbikLink.ServiceDefaults.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="Auth\" />
</ItemGroup>

</Project>
6 changes: 6 additions & 0 deletions UbikLink.Commander/UbikLink.Commander.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@UbikLink.Commander_HostAddress = http://localhost:5122

GET {{UbikLink.Commander_HostAddress}}/weatherforecast/
Accept: application/json

###
8 changes: 8 additions & 0 deletions UbikLink.Commander/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions UbikLink.Commander/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
1 change: 1 addition & 0 deletions UbikLink.Common/Api/AuthRegisterAuthKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class AuthRegisterAuthKey
{
public const string Position = "AuthRegister";
public string Key { get; set; } = string.Empty;
public string HubSignSecureKey { get; set; } = string.Empty;
public bool EmailActivationActivated { get; set; } = false;
}
}
8 changes: 4 additions & 4 deletions UbikLink.Proxy/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,25 +118,25 @@
})
.AddPolicy("CanReadTenant", policy =>
{
policy.Requirements.Add(new UserTenantRolesOrAuthorizationsRequirement(new[] { "tenant:read" }, PermissionMode.Authorization, true));
policy.Requirements.Add(new UserTenantRolesOrAuthorizationsRequirement(["tenant:read"], PermissionMode.Authorization, true));
policy.RequireAuthenticatedUser();
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
})
.AddPolicy("CanReadTenantAndReadUser", policy =>
{
policy.Requirements.Add(new UserTenantRolesOrAuthorizationsRequirement(new[] { "tenant:read", "user:read" }, PermissionMode.Authorization, true));
policy.Requirements.Add(new UserTenantRolesOrAuthorizationsRequirement(["tenant:read", "user:read"], PermissionMode.Authorization, true));
policy.RequireAuthenticatedUser();
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
})
.AddPolicy("CanReadTenantAndWriteUserRole", policy =>
{
policy.Requirements.Add(new UserTenantRolesOrAuthorizationsRequirement(new[] { "tenant:read", "user:read", "tenant-user-role:write" }, PermissionMode.Authorization, true));
policy.Requirements.Add(new UserTenantRolesOrAuthorizationsRequirement(["tenant:read", "user:read", "tenant-user-role:write"], PermissionMode.Authorization, true));
policy.RequireAuthenticatedUser();
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
})
.AddPolicy("CanReadTenantAndReadTenantRoles", policy =>
{
policy.Requirements.Add(new UserTenantRolesOrAuthorizationsRequirement(new[] { "tenant:read", "tenant-role:read" }, PermissionMode.Authorization, true));
policy.Requirements.Add(new UserTenantRolesOrAuthorizationsRequirement(["tenant:read", "tenant-role:read"], PermissionMode.Authorization, true));
policy.RequireAuthenticatedUser();
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
});
Expand Down
23 changes: 23 additions & 0 deletions UbikLink.Proxy/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,22 @@
"Methods": [ "POST" ]
},
"Transforms": [ { "PathPattern": "/api/{apiversion}/users/register" } ]
},
"route_security_user_get_hub_token": {
"ClusterId": "ubiklink-security-api",
"AuthorizationPolicy": "IsUser",
"Match": {
"Path": "/security/api/{apiversion}/hubtoken",
"Methods": [ "GET" ]
},
"Transforms": [ { "PathPattern": "/api/{apiversion}/hubtoken" } ]
},
"route_commander_chathub": {
"ClusterId": "ubiklink-commander",
"Match": {
"Path": "/chathub"
},
"Transforms": [ { "PathPattern": "/chat" } ]
}
},
"Clusters": {
Expand All @@ -94,6 +110,13 @@
"Address": "http://ubiklink-security-api"
}
}
},
"ubiklink-commander": {
"Destinations": {
"destination1": {
"Address": "http://ubiklink-commander"
}
}
}
}
}
Expand Down
26 changes: 26 additions & 0 deletions UbikLink.Security.Api/Features/Users/Errors/GetHubTokenError.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using UbikLink.Common.Errors;

namespace UbikLink.Security.Api.Features.Users.Errors
{
public record GetHubTokenError : IFeatureError
{
public FeatureErrorType ErrorType { get; init; }
public CustomError[] CustomErrors { get; init; }
public string Details => CustomErrors[0].ErrorFriendlyMessage;

public GetHubTokenError()
{

ErrorType = FeatureErrorType.BadParams;
CustomErrors = [ new()
{
ErrorCode = $"CANNOT_GET_HUB_TOKEN",
ErrorFriendlyMessage = $"The connected user request is not valid to receive a hub token.",
FieldsValuesInError = new Dictionary<string, string>
{
{ "userId", "connected user" },
}
}];
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using UbikLink.Security.Api.Features.Users.Commands.OnboardMeSimple;
using UbikLink.Security.Api.Features.Users.Commands.RegisterUser;
using UbikLink.Security.Api.Features.Users.Commands.UpdateUserSettingsMe;
using UbikLink.Security.Api.Features.Users.Queries.GetMyHubToken;
using UbikLink.Security.Api.Features.Users.Queries.GetUserForProxy;
using UbikLink.Security.Api.Features.Users.Queries.GetUserMe;
using UbikLink.Security.Api.Features.Users.Services;
Expand All @@ -24,6 +25,8 @@ public static void AddUserFeatures(this IServiceCollection services)
services.AddScoped<RegisterUserValidator>();

services.AddScoped<OnboardMeSimpleHandler>();

services.AddScoped<GetMyHubTokenHandler>();
}
}
}
Loading