source: ChapterX.API/Program.cs@ e294f7d

main
Last change on this file since e294f7d was e294f7d, checked in by kikisrbinoska <srbinoskakristina07@…>, 4 months ago

Added JWT authentication

  • Property mode set to 100644
File size: 2.5 KB
Line 
1using ChapterX.Application;
2using ChapterX.Infrastructure;
3using Microsoft.AspNetCore.Authentication.JwtBearer;
4using Microsoft.IdentityModel.Tokens;
5using System.Reflection;
6using System.Text;
7
8var builder = WebApplication.CreateBuilder(args);
9
10builder.Services.AddControllers();
11builder.Services.AddEndpointsApiExplorer();
12builder.Services.AddSwaggerGen(options =>
13{
14 options.CustomSchemaIds(type => type.FullName);
15 options.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
16 {
17 Name = "Authorization",
18 Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
19 Scheme = "Bearer",
20 BearerFormat = "JWT",
21 In = Microsoft.OpenApi.Models.ParameterLocation.Header,
22 Description = "Enter your JWT token"
23 });
24 options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
25 {
26 {
27 new Microsoft.OpenApi.Models.OpenApiSecurityScheme
28 {
29 Reference = new Microsoft.OpenApi.Models.OpenApiReference
30 {
31 Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
32 Id = "Bearer"
33 }
34 },
35 Array.Empty<string>()
36 }
37 });
38});
39
40builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
41 .AddJwtBearer(options =>
42 {
43 options.TokenValidationParameters = new TokenValidationParameters
44 {
45 ValidateIssuer = true,
46 ValidateAudience = true,
47 ValidateLifetime = true,
48 ValidateIssuerSigningKey = true,
49 ValidIssuer = builder.Configuration["Jwt:Issuer"],
50 ValidAudience = builder.Configuration["Jwt:Audience"],
51 IssuerSigningKey = new SymmetricSecurityKey(
52 Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
53 };
54 });
55builder.Services.AddAuthorization();
56
57builder.Services.AddApplication();
58builder.Services.AddInfrastructure(builder.Configuration);
59
60var app = builder.Build();
61
62if (app.Environment.IsDevelopment())
63{
64 app.UseSwagger();
65 app.UseSwaggerUI();
66}
67
68app.UseHttpsRedirection();
69app.UseAuthentication();
70app.UseAuthorization();
71try
72{
73 app.MapControllers();
74}
75catch (ReflectionTypeLoadException ex)
76{
77 Console.Error.WriteLine("ReflectionTypeLoadException while mapping controllers:");
78 foreach (var loaderEx in ex.LoaderExceptions ?? [])
79 {
80 Console.Error.WriteLine(loaderEx.ToString());
81 }
82
83 throw;
84}
85
86app.Run();
Note: See TracBrowser for help on using the repository browser.