3

I am using C# asp.net I want to use jwt token for my webpage. So whenever the page loads , i have to use jwt , im a beginner so i dont have much idea, i know how it works, but i dont know where to start from or how to implement exactly. i have a login page and i only need jwt for "online id/admin/username". Using these SymmetricSecurityKey SigningCredentials JwtHeader JwtPayload JwtSecurityToken JwtSecurityTokenHandler WriteToken var token = handler.ReadJwtToken(tokenString); and googling gives my result for .net core which is not what i want, can someone help me? Thankyou

I tried some code snippets but im sure im not doing it the right way

2 Answers 2

3

To authenticate using JWT, you must first register the user and store it in your database. When logging in and validating the user with database information, use the following code to create a JWT token.

    public static string GenerateJwtToken()
    {
        DateTime value = DateTime.Now.AddMinutes(20.0);
        byte[] bytes = Encoding.ASCII.GetBytes("MIIBrTCCAaGg ...");
        SigningCredentials signingCredentials = new SigningCredentials(new SymmetricSecurityKey(bytes), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256");
        SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
        {
            Expires = value,
            SigningCredentials = signingCredentials
        };
        JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
        SecurityToken token = jwtSecurityTokenHandler.CreateToken(tokenDescriptor);
        return jwtSecurityTokenHandler.WriteToken(token);
    }

Then, in the actions that have the Authorize attribute, you must send the token created above in the request header.

[HttpPost]
[Authorize]
public async Task<IActionResult> Test(TestRequest input)
{
    .
    .
    .
}

I wrote a simple example, you can see the complete implementation example with JWT from this link

Sign up to request clarification or add additional context in comments.

Comments

3

Program.cs

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "Please enter JWT with Bearer into field",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty<string>()
        }
    });
});


//JWT Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

app.UseAuthentication();

app.UseAuthorization();

appSetting.json

  "Jwt": {
    "Key": "aVeryLongSecretKeyThatIsAtLeast32BytesLong",
    "Issuer": "http://localhost:7123/",
    "Audience": "http://localhost:7123/"
  }

Generate Token

  private readonly IConfiguration _config;

 public JWTService(IConfiguration config)
 {
     _config = config;
 }

public string GenerateToken(UserMaster user)
   {
       var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
       var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

       var claims = new[]
       {
       new Claim(JwtRegisteredClaimNames.Sub, user.Email),
       new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
       new Claim(ClaimTypes.Role, getUserType(user.UserType))
   };

       var token = new JwtSecurityToken(
           issuer: _config["Jwt:Issuer"],
           audience: _config["Jwt:Audience"],
           claims: claims,
           expires: DateTime.Now.AddMinutes(30),
           signingCredentials: credentials
       );

       return new JwtSecurityTokenHandler().WriteToken(token);
   }

Check the Role

[Authorize(Roles = "SuperAdmin")]
[HttpPost("create-user-with-email")]
public async Task<IActionResult> Get([FromBody] CreateUserWithEmail _loginUser)
{
    var result = await _user.CreateUserWithEmail(_loginUser);
    return Ok(result);
}

2 Comments

getUserType returns a value like "SuperAdmin"?
that's correct @Jon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.