Authentication & Authorization

Altruist builds on top of .NET’s authentication system, but it also introduces its own lightweight and flexible mechanisms — especially for socket-based communication. So whether you're dealing with HTTP routes or real-time socket events, you're covered.

HTTP Authentication (via .NET)

For all your HTTP endpoints, you can use ASP.NET Core's built-in authentication system. Altruist doesn’t reinvent the wheel here — instead, it plays nicely with standard middleware like JWT, cookies, OAuth2, and more.

Setting up Authentication for the Web App

You can set up authentication using JWT tokens, cookies, or any other authentication scheme that works with ASP.NET Core.

In the AltruistBuilder configuration, you can add the authentication setup like this:

AltruistBuilder.Create(args)
    .NoEngine()
    .WithWebsocket(setup => setup.MapPortal<SimpleGamePortal>("/game"))
    .WithRedis(setup => setup.AddDocument<Spaceship>())
    .WebApp(setup =>
    {
        setup.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(jwtOptions =>
            {
                jwtOptions.Authority = "https://{--your-authority--}";
                jwtOptions.Audience = "https://{--your-audience--}";
            });

        setup.AddAuthorization(options =>
        {
            options.AddPolicy("GameAdmin", policy =>
                policy.RequireClaim("role", "admin"));
        });

        return setup;
    })
    .Configure(app =>
    {
        app.UseAuthentication();
        app.UseAuthorization();
    })
    .StartServer();

Socket Authentication (via Altruist)

This is where Altruist really shines. For socket authentication, Altruist introduces a simpler and more purpose-built solution — the Shield system — while still integrating with JWT and your existing .NET setup.

Enabling JWT for WebSockets

To authenticate WebSocket clients via JWT:

.WebApp(setup =>
{
    setup.AddJwtAuth(options =>
    {
        options.Authority = "https://your-auth-server.com";
        options.Audience = "your-audience";
    });

    return setup;
})

This sets up token validation for both HTTP and WebSocket endpoints.

🔐 Securing Portals with [Shield]

To secure a full portal, just decorate it with [JwtShield]:

[JwtShield]
public class MyPortal : AltruistGameSessionPortal<Spaceship>
{
    ...
}

This ensures that only authenticated socket clients can access this portal.

🔮 What’s Next?

Altruist will keep improving in this area with:

  • Native multi-auth provider support
  • First-class OAuth2/OpenID integrations
  • Custom token validation pipelines
  • Stay tuned. Cool stuff ahead! 🤘