Bearer-Authentifcation

This commit is contained in:
2026-03-09 12:35:11 +01:00
parent ecf84016dc
commit bbb4fec581
3 changed files with 59 additions and 67 deletions

View File

@@ -11,6 +11,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.3" />
<PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="10.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="10.1.4" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="10.1.4" />

View File

@@ -1,3 +1,6 @@
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
namespace API.Extension;
@@ -5,7 +8,7 @@ namespace API.Extension;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddWebServices(this IServiceCollection services,
ConfigurationManager builderConfiguration)
IConfiguration configuration)
{
services.AddSwaggerGen(options =>
{
@@ -13,7 +16,43 @@ public static class ServiceCollectionExtensions
options.SwaggerDoc("v1", new OpenApiInfo { Title = "DotNetAngular API", Version = "v1" });
// update names of the api
options.SwaggerGeneratorOptions.DocumentFilters.Add(new LowerCaseDocumentFilter());
// configure JWT authentication
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description =
"JWT Authorization header using the Bearer scheme. Enter your token in the text input below."
});
options.AddSecurityRequirement(doc =>
{
var schemeRef = new OpenApiSecuritySchemeReference("Bearer", doc);
return new OpenApiSecurityRequirement
{
{ schemeRef, new List<string>() }
};
});
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration["Jwt:Issuer"],
ValidAudience = configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey
(Encoding.UTF8.GetBytes(configuration["Jwt:Key"] ??
throw new InvalidOperationException("Jwt:Key is not configured"))),
ClockSkew = TimeSpan.Zero // remove delay of token expiration time
};
});
return services;
}