Posts

....
Technical Blog for .NET Developers ©

Saturday, May 25, 2024

JWT Token Validation

There are different ways and technologies to validate a JWT Token, depending on the needs of securization of the infrastructure

This article deepens on theories and techniques of JWT Token validation: How to Validate JWTs in .NET

In this example we implement automatic validation with ASP.NET Core middleware, making emphasis on validate these pieces of the token: issuer, audience, and expiration time, which are the basic pieces to be validated



With this code we generate a JWT Token, codified in a string composed by header, payload, and signature

 

    public string GenerateToken(string user)
    {
        JwtSecurityTokenHandler tokenHandler = new ();
        byte[] key = Encoding.ASCII.GetBytes("B88CF37BEEE14F9DAA10DA3BDF23D9CA6EBD06E27A6D49C2867A211685A41E88");
        SecurityTokenDescriptor tokenDescriptor = new ()
        {
            Subject = new ClaimsIdentity(new[] { new Claim("id", "user_Id") }),
            Expires = DateTime.UtcNow.AddMinutes(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
            Issuer = "https://authdomain",
            Audience = "the_audience",            
            IssuedAt = DateTime.UtcNow,
            Claims = new Dictionary<string, object> { ["claim1"] = "test" }
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }





To validate the token from the api, configure the token at IoC to validate it as it is created originally from the source

 
  
        public static void ConfigureJWTToken(this IServiceCollection services, IConfiguration configuration)
        {
            byte[] key = Encoding.ASCII.GetBytes("B88CF37BEEE14F9DAA10DA3BDF23D9CA6EBD06E27A6D49C2867A211685A41E88");

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
              .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
              {
                  options.Audience = configuration["Auth:Audience"];
                  //options.Authority : Gets or sets the Authority to use when making OpenIdConnect calls.
                  options.TokenValidationParameters =
                    new TokenValidationParameters
                    {
                        ValidateAudience = true,
                        AudienceValidator = new AudienceValidator((audiences, token, options) =>
                        {
                            // audience validator logic
                            return true;
                        }),
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero,
                        ValidateIssuer = true,
                        ValidIssuer = "https://authdomain",
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                    };
              });
        }  
  


METHOD SOFTWARE 2024

Friday, May 10, 2024

.NET Maui

.NET Multi-platform App UI (.NET MAUI) is a cross-platform framework for creating native mobile and desktop apps with C# and XAML.

Using .NET MAUI, you can develop apps that can run on Android, iOS, macOS, and Windows from a single shared code-base.

Microsoft .NET Maui

In this post we set up the environment to develop Maui Apps with Visual Studio 2022

First create a new project of type .NET Maui App, and configure the emulator of Android devices




The emulator installs a serie of tools, you can type the next command to list the Android Virtual Devices installed on the machine



Ensure that Hypervisor is operational on the machine



Start the virtual device to debug the application, notice you can configure different devices to test the application





<METHOD SOFTWARE 2024>