net core jwt authentication code example

Example 1: c# core jwt

// more generic
private string GenerateJSONWebToken()
{
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MynameisJamesBond007"));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
 
    var token = new JwtSecurityToken(
        issuer: "https://www.yogihosting.com",
        audience: "https://www.yogihosting.com",
        expires: DateTime.Now.AddHours(3),
        signingCredentials: credentials
        );
 
    return new JwtSecurityTokenHandler().WriteToken(token);
}

Example 2: c# jwt

// Startup.cs
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.SaveToken = true;
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = "https://www.yogihosting.com",
        ValidIssuer = "https://www.yogihosting.com",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MynameisJamesBond007"))
    };
});