Search code examples
c#asp.net-coreopeniddict

Get unauthorize when trying to exchange code for a token using OpenIddict


I am using OpenIddict authorization code flow with windows authentication; looked at this example everything seems to correct except I cannot exchange the code for a token, it's not even hitting the /token endpoint for some reason (I am getting 401 - Unauthorized). It's getting the code without any issue. Am I missing anything ?

I am using Net8

builder.Services.AddOpenIddict()
    .AddCore(options =>
    {
        options.UseEntityFrameworkCore()
               .UseDbContext<DbContext>();
    }).AddServer(options =>
    {

        options.AllowAuthorizationCodeFlow()
           .AllowRefreshTokenFlow();

        options.SetAuthorizationEndpointUris("authorize")
                .SetTokenEndpointUris("token");

        options.AddEncryptionKey(new SymmetricSecurityKey(Convert.FromBase64String("DRjd/GnduI3Efzen9V9BvbNUfc/VKgXltV7Kbk9sMkY=")));

        options.AddDevelopmentSigningCertificate();

        options.UseAspNetCore()
                .EnableTokenEndpointPassthrough()
                .EnableAuthorizationEndpointPassthrough();
    })

     .AddValidation(options =>
    {
        options.UseLocalServer();
        options.UseAspNetCore();
    });
builder.Services.AddAuthorization();

var app = builder.Build();

Adding the App

await using (var scope = app.Services.CreateAsyncScope())
{
    var context = scope.ServiceProvider.GetRequiredService<DbContext>();
    await context.Database.EnsureCreatedAsync();
    var manager = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();
    await manager.CreateAsync(new OpenIddictApplicationDescriptor
    {
        ClientId = "console_app",
        RedirectUris =
                {
                    new Uri("https://oauth.pstmn.io/v1/callback")
                },
        Permissions =
                {
                    Permissions.Endpoints.Authorization,
                    Permissions.Endpoints.Token,
                    Permissions.GrantTypes.AuthorizationCode,
                    Permissions.ResponseTypes.Code,
                    Permissions.ResponseTypes.Token
                }
    });
}

Endpoints

app.MapGet("/authorize", (HttpContext context, IOpenIddictScopeManager manager) =>
{
    var identity = new ClaimsIdentity(
       authenticationType: TokenValidationParameters.DefaultAuthenticationType,
       nameType: Claims.Name,
       roleType: Claims.Role);
    identity.AddClaim(new Claim(Claims.Subject, context!.User!.Identity!.Name!.ToString(CultureInfo.InvariantCulture)));
    identity.SetDestinations(claim => [Destinations.AccessToken]);

    return Results.SignIn(new ClaimsPrincipal(identity), properties: null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}).RequireAuthorization();

app.MapPost("/token", (HttpContext context, IOpenIddictScopeManager manager) =>
{
    return Results.Ok("");
}));

app.Run();

Solution

  • After some investigating, the issue was fixed by allowing Windows authentication and anonymous. the token segment usea basic authentication.