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?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,639 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
346 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,271 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 67,251 Reputation points
    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 Answers by the question author, which helps users to know the answer solved the author's problem.