Skip to content

Commit

Permalink
enable opentelemetry
Browse files Browse the repository at this point in the history
  • Loading branch information
Barsonax committed May 24, 2024
1 parent eceaf85 commit c715a24
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 51 deletions.
2 changes: 1 addition & 1 deletion CleanAspCore.Api.Tests/CleanAspCore.Api.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.4"/>

<PackageReference Include="Testcontainers.PostgreSql" Version="3.8.0"/>
<PackageReference Include="Npgsql" Version="8.0.2"/>
<PackageReference Include="Npgsql" Version="8.0.3"/>
<PackageReference Include="Respawn" Version="6.2.1"/>

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0"/>
Expand Down
76 changes: 71 additions & 5 deletions CleanAspCore/AppConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
using System.Net;
using System.Reflection;
using CleanAspCore.Endpoints.Departments;
using CleanAspCore.Endpoints.Employees;
using CleanAspCore.Endpoints.Jobs;
using MicroElements.Swashbuckle.FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

namespace CleanAspCore;

Expand All @@ -19,8 +27,66 @@ internal static void AddAppRoutes(this IEndpointRouteBuilder host)
host.AddJobsRoutes();
}

public static RouteHandlerBuilder RequireAuthorization(this RouteHandlerBuilder builder, params string[] policyNames) =>
AuthorizationEndpointConventionBuilderExtensions.RequireAuthorization(builder, policyNames)
.Produces((int)HttpStatusCode.Unauthorized)
.Produces((int)HttpStatusCode.Forbidden);
internal static void AddAuthServices(this WebApplicationBuilder builder)
{
builder.Services.AddAuthorizationBuilder()
.AddFallbackPolicy("Fallback", new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build());

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme);
}

internal static void AddSwaggerServices(this WebApplicationBuilder builder)
{
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SupportNonNullableReferenceTypes();

var xmlDocPath = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
options.IncludeXmlComments(xmlDocPath);

var jwtSecurityScheme = new OpenApiSecurityScheme
{
BearerFormat = "JWT",
Name = "JWT Authentication",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = JwtBearerDefaults.AuthenticationScheme,
Description = "Put **_ONLY_** your JWT Bearer token on textbox below!",
Reference = new OpenApiReference
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};

options.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);

options.AddSecurityRequirement(new OpenApiSecurityRequirement { { jwtSecurityScheme, Array.Empty<string>() } });
});
builder.Services.AddFluentValidationRulesToSwagger();
}

internal static void AddOpenTelemetryServices(this WebApplicationBuilder builder)
{
builder.Logging.AddOpenTelemetry(options =>
{
options
.SetResourceBuilder(
ResourceBuilder.CreateDefault()
.AddService(builder.Environment.ApplicationName))
.AddOtlpExporter();
});
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService(builder.Environment.ApplicationName))
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddOtlpExporter())
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddOtlpExporter());
}
}
3 changes: 3 additions & 0 deletions CleanAspCore/CleanAspCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="8.0.4"/>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.2"/>
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.8.1"/>
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.8.1"/>
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.8.1"/>
<PackageReference Include="Polly.Contrib.WaitAndRetry" Version="1.1.1"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/>
</ItemGroup>
Expand Down
11 changes: 11 additions & 0 deletions CleanAspCore/Extensions/RouteHandler/RouteHandlerExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Net;

namespace CleanAspCore.Extensions.RouteHandler;

public static class RouteHandlerExtensions
{
public static RouteHandlerBuilder RequireAuthorization(this RouteHandlerBuilder builder, params string[] policyNames) =>
AuthorizationEndpointConventionBuilderExtensions.RequireAuthorization(builder, policyNames)
.Produces((int)HttpStatusCode.Unauthorized)
.Produces((int)HttpStatusCode.Forbidden);
}
51 changes: 6 additions & 45 deletions CleanAspCore/Program.cs
Original file line number Diff line number Diff line change
@@ -1,54 +1,13 @@
using System.Reflection;
using CleanAspCore;
using CleanAspCore.Data;
using MicroElements.Swashbuckle.FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SupportNonNullableReferenceTypes();

var xmlDocPath = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
options.IncludeXmlComments(xmlDocPath);

var jwtSecurityScheme = new OpenApiSecurityScheme
{
BearerFormat = "JWT",
Name = "JWT Authentication",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = JwtBearerDefaults.AuthenticationScheme,
Description = "Put **_ONLY_** your JWT Bearer token on textbox below!",

Reference = new OpenApiReference
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};

options.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);

options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{ jwtSecurityScheme, Array.Empty<string>() }
});
});
builder.Services.AddFluentValidationRulesToSwagger();

builder.Services.AddAuthorizationBuilder()
.AddFallbackPolicy("Fallback", new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build());

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme);
builder.AddSwaggerServices();
builder.AddAuthServices();
builder.AddAppServices();
builder.AddOpenTelemetryServices();

builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), includeInternalTypes: true);
builder.Services.AddDbContext<HrContext>();
Expand All @@ -73,5 +32,7 @@

namespace CleanAspCore
{
public partial class Program { }
public partial class Program
{
}
}
8 changes: 8 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,11 @@ services:
- POSTGRES_DB=postgres
ports:
- "5432:5432"
telemetryDashboard:
image: mcr.microsoft.com/dotnet/nightly/aspire-dashboard:latest
container_name: "telemetryDashboard"
environment:
- DOTNET_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS=true
ports:
- "127.0.0.1:18888:18888"
- "127.0.0.1:4317:18889"

0 comments on commit c715a24

Please sign in to comment.