1

I use Swagger in my project, and I need to verify the process. Now, how do I implement it, like this.

enter image description here

I need to click on the verify button and then verify, I am very bad now and don't know how to do it. I read some articles, but I can't implement it. Any help is greatly appreciated.

Helen
  • 87,344
  • 17
  • 243
  • 314
  • 2
    What "verify" button? There's no "verify" button on your screenshot. Can you please explain in a bit more detail what you are trying to accomplish? In the current form, its unclear what you are asking. – Helen Nov 14 '21 at 13:42
  • You should have a method that returns a token after login, then you should take this token and enter 'Bearer' [space] and then your token in the text input that appears when you click on Authorize button. What is your problem with the previous steps? – Merna Mustafa Nov 14 '21 at 14:03
  • Your verification is to return a token after the user logs in, and then verify on the Authorize of swagger? – Tupac Nov 15 '21 at 07:45
  • @ Merna Mustafa Yes, as you said, I need it, can you give me an example? thank you very much! – Andhra Pradesh Nov 15 '21 at 23:41
  • @Chaodeng yes!What should i do – Andhra Pradesh Nov 15 '21 at 23:42
  • 2
    @AndhraPradesh Sure, but first could you please edit your question and provide your code and what you have tried till now? – Merna Mustafa Nov 16 '21 at 05:45
  • Have a look at this link [Authentication And Authorization Using JWT Token And Swagger UI](https://www.c-sharpcorner.com/article/authentication-authorization-using-net-core-web-api-using-jwt-token-and/) – Merna Mustafa Nov 16 '21 at 05:52

1 Answers1

2

I read some documents, and finally realized the process of verifying after the user logs in to generate jwt, you can refer to it.

Demonstration results:

enter image description here

First,open the appsettings.json file and change the section named Jwt:

"Jwt": {
    "Issuer": "testUser",
    "Audience": "user",
    "Key": "this is my custom Secret key for authnetication"
  }

The key here must be long enough, otherwise you will encounter related errors, which I encountered.

Enable the JWT authentication scheme and swagger authorization configuration when the configuration starts, the entire code is as follows:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using WebApplication129.Controllers.conf;

namespace WebApplication129
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddSingleton<IConfiguration>(Configuration);
            services.AddAuthentication(opt => {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
     .AddJwtBearer(options =>
     {
         options.TokenValidationParameters = new TokenValidationParameters
         {
             ValidateIssuer = true,
             ValidateAudience = true,
             ValidateLifetime = true,
             ValidateIssuerSigningKey = true,
             ValidIssuer = Configuration["Jwt:Issuer"],
             ValidAudience = Configuration["Jwt:Audience"],
             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
         };
     });
            services.AddControllers(options =>
            {
                options.Conventions.Add(new GroupingByNamespaceConvention());
            });

            services.AddSwaggerGen(config =>
            {   
                config.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description =
        "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer",
                    BearerFormat="JWT"
                });

                config.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
            },
            Scheme = "oauth2",
            Name = "Bearer",
            In = ParameterLocation.Header,

        },
        new List<string>()
    }
});


                var titleBase = "Test API";
                var description = "This is a Web API for Test operations";
                var TermsOfService = new Uri("https://xxxxxx");
                var License = new OpenApiLicense()
                {
                    Name = "MIT"
                };
                var Contact = new OpenApiContact()
                {
                    Name = "Test",
                    Email = "Test@hotmail.com",
                    Url = new Uri("https://xxxxxx")
                };

                config.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = titleBase + " v1",
                    Description = description,
                    TermsOfService = TermsOfService,
                    License = License,
                    Contact = Contact
                });

                config.SwaggerDoc("v2", new OpenApiInfo
                {
                    Version = "v2",
                    Title = titleBase + " v2",
                    Description = description,
                    TermsOfService = TermsOfService,
                    License = License,
                    Contact = Contact
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                config.IncludeXmlComments(xmlPath);
            });
        }

       
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(config =>
            {
                config.SwaggerEndpoint("/swagger/v1/swagger.json", "Test v1");
                //config.SwaggerEndpoint("/swagger/v2/swagger.json", "Test v2");
            });
            app.UseHttpsRedirection();

            app.UseAuthentication();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Log in and generate the jwt part as follows. Since I did not use it with a database, I customized a user:

Model:

public class Usuario
    {
        public string NomeUsuario { get; set; }
        public string Senha { get; set; }
    }

Controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApplication129.Model;

namespace WebApplication129.Controllers.V1
{
    [Route("api/[controller]")]
    [ApiController]
    public class SegurancaController : Controller
    {
        private IConfiguration _config;
        public SegurancaController(IConfiguration Configuration)
        {
            _config = Configuration;
        }
        [HttpPost]
        [Route("login")]
        public IActionResult Login([FromBody] Usuario loginDetalhes)
        {
            bool resultado = ValidarUsuario(loginDetalhes);
            if (resultado)
            {
                var tokenString = GerarTokenJWT();
                return Ok(new { token = tokenString });
            }
            else
            {
                return Unauthorized();
            }
        }
        private string GerarTokenJWT()
        {
            var issuer = _config["Jwt:Issuer"];
            var audience = _config["Jwt:Audience"];
            var expiry = DateTime.Now.AddMinutes(120);
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(issuer: issuer, audience: audience,
expires: expiry, signingCredentials: credentials);
            var tokenHandler = new JwtSecurityTokenHandler();
            var stringToken = tokenHandler.WriteToken(token);
            return stringToken;
        }
        private bool ValidarUsuario(Usuario loginDetalhes)
        {
            if (loginDetalhes.NomeUsuario == "TestName" && loginDetalhes.Senha == "TestPwd")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

Test and verify API:

 [Route("list_data")]
        [HttpGet]
        [Authorize]
        public Object  Data()
        {
            User user = new User();
            user.id = 1;
            user.userName = "Test";
            user.email = "test@xxx.com";
            user.address = "testAddress";

            return user;
        }

The above code can complete the function you need. For details, I refer to these documents. There are specific code descriptions. You can refer to:

ASP.NET Core - Implementando Json Web Tokens(JWT) - I

Setting up Swagger (ASP.NET Core) using the Authorization headers (Bearer)

Tupac
  • 2,590
  • 2
  • 6
  • 19