feature-request: add dotnet/C# support #1287

Closed
opened 2026-03-13 08:31:24 -05:00 by GiteaMirror · 7 comments
Owner

Originally created by @biegehydra on GitHub (May 31, 2025).

I'd like there to be some better auth nuget packages that add support for better auth. Let's use this issue to see how much the community wants it. React to this issue if you are interested

With enough traction, I will start a repo and begin working on this

Originally created by @biegehydra on GitHub (May 31, 2025). I'd like there to be some better auth nuget packages that add support for better auth. Let's use this issue to see how much the community wants it. React to this issue if you are interested With enough traction, I will start a repo and begin working on this
Author
Owner

@yigsvnsla commented on GitHub (Jun 1, 2025):

You can easily use the open-api implementation that already comes in the core plugins.

@yigsvnsla commented on GitHub (Jun 1, 2025): You can easily use the open-api implementation that already comes in the core plugins.
Author
Owner

@biegehydra commented on GitHub (Jun 1, 2025):

I'd have to look into it but there's a lot more that goes into it. A good package would have a middleware, repository service, authentication/authorization service, endpoint/controller attributes, etc

@biegehydra commented on GitHub (Jun 1, 2025): I'd have to look into it but there's a lot more that goes into it. A good package would have a middleware, repository service, authentication/authorization service, endpoint/controller attributes, etc
Author
Owner

@ChristPetitjean commented on GitHub (Jun 2, 2025):

Hello, i was wondering if I was alone with this exact requirement.

I was thinking of a nuxt frontend with a dotnet backend to be able to scale only the backend if needed but keep the front with some ssr capabilities.

So, yes, I follow you 😜

@ChristPetitjean commented on GitHub (Jun 2, 2025): Hello, i was wondering if I was alone with this exact requirement. I was thinking of a nuxt frontend with a dotnet backend to be able to scale only the backend if needed but keep the front with some ssr capabilities. So, yes, I follow you 😜
Author
Owner

@ChristPetitjean commented on GitHub (Jun 3, 2025):

I'd have to look into it but there's a lot more that goes into it. A good package would have a middleware, repository service, authentication/authorization service, endpoint/controller attributes, etc

For better compatibilty with dotnet, you should not provide endpoints.
"Endpoint / controller / AWS Lambda / Azure function, etc.", are all possible solutions and choosing one will prevent other (of course)
So maybe just a set of handful services that everyone if free to map to their prefered/mandatory stack with some guidance.

Something like :

Service:

public interface IBetterAuthService 
{
    SignInResult HandleSignIn(SignInInput input);
}

Usage:

Call IBetterAuthService service from your prefered stack.
You have to map:

  • for signin:
    • route: /auth/signin
    • verb: POST
    • service: IBetterAuthService
    • method to call: HandleSignIn
  • for singup:
    • route: /auth/signup
    • verb: POST
    • service: IBetterAuthService
    • method to call: HandleSignUp

Some naive examples below.

Minimal API:

app.MapPost("/auth/signin", [FromBody] SignInInput input, [FromService] BetterService betterService) => 
    betterService.HandleSignIn(signInInput)?.ToResult() ?? Results.Problem("Something gone wrong !");

Controller:

[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
    private readonly IBetterAuthService _betterAuthService;
    private AuthController(IBetterAuthService betterAuthService)
    {
        _betterAuthService = betterAuthService;
    }

    [HttpPost]
    public IActionResult SignIn(SignInInput signInInput)
    {
        var result = _betterAuthService.HandleSignIn(signInInput);
        if (result == null)
        {
            return Results.Problem("Something gone wrong !");
        }
        return Ok(result);
    }
}

Azure function

public class SigninEndpoint(
    ILogger<SigninEndpoint> logger,
    IBetterAuthService betterAuthService)
{
    [Function("signin")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth/signin")]
        HttpRequest req,
        SignInInput input,
        CancellationToken cancellationToken)
    {
        var result = betterAuthService.HandleSignIn(signInInput);
        if (result == null)
        {
            return Results.Problem("Something gone wrong !");
        }
        return Ok(result);
    }
}
@ChristPetitjean commented on GitHub (Jun 3, 2025): > I'd have to look into it but there's a lot more that goes into it. A good package would have a middleware, repository service, authentication/authorization service, endpoint/controller attributes, etc For better compatibilty with dotnet, you should not provide endpoints. "Endpoint / controller / AWS Lambda / Azure function, etc.", are all possible solutions and choosing one will prevent other (of course) So maybe just a set of handful services that everyone if free to map to their prefered/mandatory stack with some guidance. Something like : ## Service: ```csharp public interface IBetterAuthService { SignInResult HandleSignIn(SignInInput input); } ``` # Usage: Call `IBetterAuthService` service from your prefered stack. You have to map: - for signin: - route: /auth/signin - verb: POST - service: IBetterAuthService - method to call: HandleSignIn - for singup: - route: /auth/signup - verb: POST - service: IBetterAuthService - method to call: HandleSignUp Some naive examples below. ## Minimal API: ```csharp app.MapPost("/auth/signin", [FromBody] SignInInput input, [FromService] BetterService betterService) => betterService.HandleSignIn(signInInput)?.ToResult() ?? Results.Problem("Something gone wrong !"); ``` ## Controller: ```csharp [ApiController] [Route("[controller]")] public class AuthController : ControllerBase { private readonly IBetterAuthService _betterAuthService; private AuthController(IBetterAuthService betterAuthService) { _betterAuthService = betterAuthService; } [HttpPost] public IActionResult SignIn(SignInInput signInInput) { var result = _betterAuthService.HandleSignIn(signInInput); if (result == null) { return Results.Problem("Something gone wrong !"); } return Ok(result); } } ``` ## Azure function ```csharp public class SigninEndpoint( ILogger<SigninEndpoint> logger, IBetterAuthService betterAuthService) { [Function("signin")] public async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth/signin")] HttpRequest req, SignInInput input, CancellationToken cancellationToken) { var result = betterAuthService.HandleSignIn(signInInput); if (result == null) { return Results.Problem("Something gone wrong !"); } return Ok(result); } } ```
Author
Owner

@yigsvnsla commented on GitHub (Jun 3, 2025):

I'd like there to be some better auth nuget packages that add support for better auth. Let's use this issue to see how much the community wants it. React to this issue if you are interested

With enough traction, I will start a repo and begin working on this

I don't know what your experience is like as a dev, but just google a little and investigate how the open API standard works and you'll realize that you don't need to write almost any code since you could delegate everything to a service layer or directly within the services you already have, call the fetch client.

https://learn.microsoft.com/en-us/openapi/kiota/install?tabs=bash

https://stackoverflow.com/questions/73877723/how-to-generate-openapi-client-sdk-project-in-net-core

@yigsvnsla commented on GitHub (Jun 3, 2025): > I'd like there to be some better auth nuget packages that add support for better auth. Let's use this issue to see how much the community wants it. React to this issue if you are interested > > With enough traction, I will start a repo and begin working on this I don't know what your experience is like as a dev, but just google a little and investigate how the open API standard works and you'll realize that you don't need to write almost any code since you could delegate everything to a service layer or directly within the services you already have, call the fetch client. https://learn.microsoft.com/en-us/openapi/kiota/install?tabs=bash https://stackoverflow.com/questions/73877723/how-to-generate-openapi-client-sdk-project-in-net-core
Author
Owner

@biegehydra commented on GitHub (Jun 3, 2025):

@yigsvnsla Quite experienced. I'm very familiar with OpenApi specs. The goal is not for my asp.net to be a client, its for it to be the server... I don't want to have a separate js backend. I want my asp.net backend to be able to hook into the better-auth framework and be able to issue tokens, manage sessions, authenticate, authorize, etc. All by only interacting with the database that follows the better-auth specs.

I'm sure I could create an authentication service that acts as a proxy to a javascript backend but that has many downsides:

  • Requires extra application
  • Extra rounded-trip (increased delay)
  • Lacks actual asp.net integration (as mentioned before, authorization attributes, services, identity integration)
  • Makes transactions & consistency more difficult
  • Monorepos are easier to manage and track issues/logs

It seems like you are not familiar with asp.net because it should be pretty clear why a nuget package would be quite useful. All I want to do to use better auth is this:

dotnet add package BetterAuth
builder.Services.AddBetterAuth();

app.UseBetterAuth();

[Authorize(AuthenticationSchemes = "BetterAuth")] 
public class MyController
{
    // Protected by better-auth
    [HttpGet("/api/my-endpoint")]
    public string MyEndpoint() => "Success";
}

Also, being able to inject an authentication/authorization service directly into my blazor components would be a godsend.

Your solution would require about 100x more work on my end.

@biegehydra commented on GitHub (Jun 3, 2025): @yigsvnsla Quite experienced. I'm very familiar with OpenApi specs. The goal is not for my asp.net to be a client, its for it to be the server... I don't want to have a separate js backend. I want my asp.net backend to be able to hook into the better-auth framework and be able to issue tokens, manage sessions, authenticate, authorize, etc. All by only interacting with the database that follows the better-auth specs. I'm sure I could create an authentication service that acts as a proxy to a javascript backend but that has many downsides: - Requires extra application - Extra rounded-trip (increased delay) - Lacks actual asp.net integration (as mentioned before, authorization attributes, services, identity integration) - Makes transactions & consistency more difficult - Monorepos are easier to manage and track issues/logs It seems like you are not familiar with asp.net because it should be pretty clear why a nuget package would be quite useful. All I want to do to use better auth is this: ```bash dotnet add package BetterAuth ``` ```cs builder.Services.AddBetterAuth(); app.UseBetterAuth(); [Authorize(AuthenticationSchemes = "BetterAuth")] public class MyController { // Protected by better-auth [HttpGet("/api/my-endpoint")] public string MyEndpoint() => "Success"; } ``` Also, being able to inject an authentication/authorization service directly into my blazor components would be a godsend. Your solution would require about 100x more work on my end.
Author
Owner

@yigsvnsla commented on GitHub (Jun 3, 2025):

@yigsvnslaTengo bastante experiencia. Estoy muy familiarizado con las especificaciones de OpenAPI. El objetivo no es que mi ASP.NET sea un cliente, sino el servidor. No quiero tener un backend de JavaScript independiente. Quiero que mi backend de ASP.NET cumpla con las especificaciones/marco de Better-Auth y pueda emitir tokens, gestionar sesiones, autenticar, autorizar, etc. Todo ello interactuando únicamente con la base de datos que cumple con dichas especificaciones.

Estoy seguro de que podría crear un servicio de autenticación que actúe como proxy de un backend de JavaScript, pero eso tiene muchas desventajas:

  • Requiere aplicación adicional
  • Viaje de ida y vuelta adicional (mayor retraso)
  • Carece de integración real con asp.net (como se mencionó anteriormente, atributos de autorización, servicios, integración de identidad)
  • Dificulta las transacciones y la consistencia
  • Los monorepositorios son más fáciles de administrar y rastrear problemas/registros.

Parece que no estás familiarizado con ASP.NET, ya que debería estar bastante claro por qué un paquete NuGet sería tan útil. Lo único que quiero hacer para usar una mejor autenticación es esto:

dotnet add package BetterAuth
builder.Services.AddBetterAuth();

app.UseBetterAuth();

[Authorize(AuthenticationSchemes = "BetterAuth")]
public class MyController
{
// Protected by better-auth
[HttpGet("/api/my-endpoint")]
public string MyEndpoint() => "Success";
}
Su solución requeriría aproximadamente 100 veces más trabajo de mi parte.

I understand your point, but keep in mind that better-auth is a project in development. Underneath, better-auth uses better-fetch, which is basically a wrapper for "fetch" on the client side, and on the server side, things are getting more complex.

That said, I feel like better-auth is still in the development phase, and I don't think they'll be willing to create an SDK for other languages ​​unless the community itself pushes for it with its own implementations.

On the other hand, you don't really need to modify much to use better-auth. I prefer to have it separate rather than within my API. Just keep in mind that one day I want to switch from better-auth to another authentication provider (Keycloak, Zitadel, Clerk, my own custom authentication API). I'll need to decouple a few things, which would take time and complexity.

That's my opinion, hehe. I'm just reflecting on the topic.

@yigsvnsla commented on GitHub (Jun 3, 2025): > [@yigsvnsla](https://github.com/yigsvnsla)Tengo bastante experiencia. Estoy muy familiarizado con las especificaciones de OpenAPI. El objetivo no es que mi ASP.NET sea un cliente, sino el servidor. No quiero tener un backend de JavaScript independiente. Quiero que mi backend de ASP.NET cumpla con las especificaciones/marco de Better-Auth y pueda emitir tokens, gestionar sesiones, autenticar, autorizar, etc. Todo ello interactuando únicamente con la base de datos que cumple con dichas especificaciones. > > Estoy seguro de que podría crear un servicio de autenticación que actúe como proxy de un backend de JavaScript, pero eso tiene muchas desventajas: > > * Requiere aplicación adicional > * Viaje de ida y vuelta adicional (mayor retraso) > * Carece de integración real con asp.net (como se mencionó anteriormente, atributos de autorización, servicios, integración de identidad) > * Dificulta las transacciones y la consistencia > * Los monorepositorios son más fáciles de administrar y rastrear problemas/registros. > > Parece que no estás familiarizado con ASP.NET, ya que debería estar bastante claro por qué un paquete NuGet sería tan útil. Lo único que quiero hacer para usar una mejor autenticación es esto: > > dotnet add package BetterAuth > builder.Services.AddBetterAuth(); > > app.UseBetterAuth(); > > [Authorize(AuthenticationSchemes = "BetterAuth")] > public class MyController > { > // Protected by better-auth > [HttpGet("/api/my-endpoint")] > public string MyEndpoint() => "Success"; > } > Su solución requeriría aproximadamente 100 veces más trabajo de mi parte. I understand your point, but keep in mind that better-auth is a project in development. Underneath, better-auth uses better-fetch, which is basically a wrapper for "fetch" on the client side, and on the server side, things are getting more complex. That said, I feel like better-auth is still in the development phase, and I don't think they'll be willing to create an SDK for other languages ​​unless the community itself pushes for it with its own implementations. On the other hand, you don't really need to modify much to use better-auth. I prefer to have it separate rather than within my API. Just keep in mind that one day I want to switch from better-auth to another authentication provider (Keycloak, Zitadel, Clerk, my own custom authentication API). I'll need to decouple a few things, which would take time and complexity. That's my opinion, hehe. I'm just reflecting on the topic.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1287