Add JWT Bearer Authorization to Swagger and ASP.NET Core

Written by ppolyzos

Software engineer based in beautiful Luxembourg


    1. ppolyzos

      For swagger 2.x I have used the following code:

      var security = new Dictionary>
          {"Bearer", new string[] { }},
      c.AddSecurityDefinition("Bearer", new ApiKeyScheme
          Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
          Name = "Authorization",
          In = "header",
          Type = "apiKey"

    This is great, but kinda sucks that it doesn’t remember the token when you refresh the page.

    Is there anything planned or possible with that?
    (right now I’m keeping notepad open with a token to copy each time i recompile)

    1. ppolyzos

      You can use the `[AllowAnonymous]` attribute if you want your API endpoint to be public.
      Otherwise use `[Authorized(Roles=”Admin”)]` for Role-based Authentication or `[Authorize(Policy = “EmployeeOnly”)]` for claims-based authorization.
      You can read more here and here if you want to do filtering based on security policies in Swagger.

  2. Themistoklis

    Why does not work the [Authorized(Roles=”Admin”)] ?

    I am using the below code in StartUp.cs.

    services.AddSwaggerGen(t =>
    t.SwaggerDoc(“v1”, new OpenApiInfo() { Title = “RestaurantApp”, Version = “Version1” });
    new OpenApiSecurityScheme
    Description = “Roles required: Admin”,
    Name = “Authorization”,
    In = ParameterLocation.Header,
    Type = SecuritySchemeType.ApiKey,
    Also, in my controller I am using [Authorized(Roles=”Admin”)] . My program is working correctly in Postman.

    Thank you.

      1. Themistoklis

        I have tried the same code with Postman and is running correctly. The code is:
        [Authorize(Roles = Role.Admin)]
        public async Task GetAllCustomers()
        var customers = await _customerService.GetAllCustomersAsync();
        return Ok(customers);
        The problem is that it can not be Authorized with swagger . In postman ,it is working. If I delete the [Authorize(Roles = Role.Admin)] command , it’s running. Also, if I am using [Authorize] is running correctly. Something is going wrong with swagger documentation and [Authorize(Roles = Role.Admin)] command.

        Thank you!

Leave a Comment
