Share via

ASP.NET API + Swagger + Azure B2C

Bernhard S 126 Reputation points
2024-10-19T09:59:42.05+00:00

This is my 3. try to get help for a ASP.NET Core + Swagger + Azure B2C demo project. I am not sending code because this results into this

https://learn.microsoft.com/en-us/answers/questions/2107081/critical-error-ask-a-question-)-page-not-found?comment=question-page-not-found?comment=question)

Has anyone a short demo for me to make a swagger page that has the endpoint "/test" to verify that the authentication with the bearer token worked?

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | ASP.NET API
Microsoft Security | Microsoft Entra | Microsoft Entra ID
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 83,421 Reputation points Volunteer Moderator
    2024-10-21T20:18:25.39+00:00

    first you need an anonymous endpoint that allows login and returns a valid token:

    https://learn.microsoft.com/en-us/azure/active-directory-b2c/access-tokens

    you can skip this if you already have a way to get the access token value

    then add token support to swagger

    builder.Services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Test01", Version = "v1" });
        c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
        {
            Name = "Authorization",
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer",
            BearerFormat = "JWT",
            In = ParameterLocation.Header,
            Description = "JWT Authorization header value: Bearer {token}"
        });
        c.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                     Reference = new OpenApiReference
                     {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                     }
                },
                new string[] {}
             }
        });
    });
    

    in the swagger ui via authorize, you can enter the token header value ("Bearer {token}") using the token the login action returns


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.