jwt token c# code example

Example 1: validate jwt token c#

public static Task<IPrincipal> validateToken(string token)
        {
            ClaimsPrincipal principal = getPrincipal(token);
            if (principal == null)
                return null;
            ClaimsIdentity identity = null;
            try
            {
                identity = (ClaimsIdentity)principal.Identity;
                IPrincipal Iprincipal = new ClaimsPrincipal(identity);
                return Task.FromResult(Iprincipal);
            }
            catch (NullReferenceException)
            {
                return Task.FromResult<IPrincipal>(null);
            }
        }

 private static ClaimsPrincipal getPrincipal(string token)
        {
            try
            {
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                JwtSecurityToken jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token);
                if (jwtToken == null)
                    return null;
                byte[] key = Encoding.ASCII.GetBytes(config.jwtSecret);
                TokenValidationParameters parameters = new TokenValidationParameters()
                {
                    ValidIssuer = config.jwtIssuer,
                    ValidAudience = config.jwtIssuer,
                    ValidateLifetime = true,
                    RequireExpirationTime = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ClockSkew = TimeSpan.Zero
                };
                SecurityToken securityToken;
                ClaimsPrincipal principal = tokenHandler.ValidateToken(token,
                      parameters, out securityToken);
                return principal;
            }
            catch
            {
                return null;
            }
  }

Example 2: c# asp.net mvc core implementing jwt

// .net token
private string GenerateJSONWebToken(UserModel userInfo)    
{    
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));    
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);    
    
    var claims = new[] {    
        new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username),    
        new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress),    
        new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")),    
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())    
    };    
    
    var token = new JwtSecurityToken(_config["Jwt:Issuer"],    
        _config["Jwt:Issuer"],    
        claims,    
        expires: DateTime.Now.AddMinutes(120),    
        signingCredentials: credentials);    
    
    return new JwtSecurityTokenHandler().WriteToken(token);    
}

Example 3: 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"))
    };
});

Example 4: jwt authentication filter c#

using System;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;
namespace myspace.filters
{
    public class JwtAuthenticationAttribute : Attribute, IAuthenticationFilter
    {
        private ILog log = LogFactory.GetLogger("JwtAuthValidationLogs");


        public string Realm { get; set; }
        public bool AllowMultiple => false;

        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            log.Info("Authenticating JWT");
            
            var request = context.Request;
            var authorization = request.Headers.Authorization;

            if (authorization == null || authorization.Scheme != "Bearer")
            {
                context.ErrorResult = new AuthenticationFailureResult("Missing Jwt Token", request);
                return;
            }

            if (string.IsNullOrEmpty(authorization.Parameter))
            {
                context.ErrorResult = new AuthenticationFailureResult("Missing Jwt Token", request);
                return;
            }

            var token = authorization.Parameter;
            try
            {
                IPrincipal principal = await SecurityUtils.validateToken(token);

                if (principal == null)
                {
                    context.ErrorResult = new AuthenticationFailureResult("Invalid token", request);

                }
                else
                {
                    context.Principal = principal;
                }

            }
            catch (Exception ex)
            {
                log.Error("Exception occured Validating Jwt Token "+ ex.Message + " Inner Exception : " + ex.InnerException);
                context.ErrorResult = new AuthenticationFailureResult("Invalid token", request);
            }
        }
        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {

            return Task.FromResult(0);
        }




    }
}