0

I have relearned asp.net core, and in my personal project, I used swagger interface documentation. I follow this documentation and it works fine, https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-3.1. But I have a doubt, that is how to use the token, I am using the asp.net core 3.1 version. As shown in my picture, although it is not done by asp.net core, how can it be implemented in .net core?

enter image description here

When I access an interface, I need a login token because I don't have permission. Can I use the global token in asp.net core?

Bihar
  • 3
  • 1

1 Answers1

1

You want to generate a token by logging in, and then pass in this token to access some permission API, right?

You can refer to this code:

services.AddSwaggerGen(config =>
            {   
                      ////Name the security scheme
                config.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "bearer",
                    BearerFormat="JWT"
                });

                config.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,

           //The name of the previously defined security scheme.
                Id = "Bearer"
            }

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

Code to generate token:

appsettings.json:

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

 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;
        }

Login to generate token:

enter image description here

Then verify:

enter image description here

Tupac
  • 2,590
  • 2
  • 6
  • 19