-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
141 lines (128 loc) · 4.94 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
global using Microsoft.AspNetCore.Authentication.JwtBearer;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.IdentityModel.Tokens;
global using SuperHeroApi.DataAccess.Data;
using FluentValidation;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.OpenApi.Models;
using SuperHeroApi.DataAccess.Models;
using SuperHeroApi.Services;
using SuperHeroApi.Validators;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Carter;
using SuperHeroApi.EndPoints;
using SuperHeroApi.Middlewares;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped<IValidator<SuperHero>, SuperHeroValidator>();
builder.Services.AddSingleton<IUserService, UserService>();
builder.Services.AddDbContext<DataContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddCarter();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Name = "Authorization",
Description = "Bearer Authentication with JWT Token",
Type = SecuritySchemeType.Http
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateActor = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
builder.Services.AddCors(options => options.AddPolicy(name: "SuperHeroOrigins",
policy => policy.WithOrigins(builder.Configuration.GetSection("AllowedOrigins").Get<string[]>())
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Authorization")));
builder.Services.AddControllers(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddAutoMapper(typeof(Program).Assembly);
builder.Services.AddTransient<GlobalExceptionHandlingMiddleware>(); /* IMiddleware approach */
WebApplication app = builder.Build();
if (app.Environment.IsDevelopment())
{
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();
}
{
app.MapGet("/", () => "Hello dumbass!").ExcludeFromDescription();
app.MapPost("/login", (UserLogin user, IUserService service) => Login(user, service))
.Accepts<UserLogin>("application/json")
.Produces<string>();
IResult Login(UserLogin user, IUserService service)
{
if (!string.IsNullOrEmpty(user.Username) && !string.IsNullOrEmpty(user.Password))
{
var loggedInUser = service.Get(user);
if (loggedInUser is null) return Results.NotFound("User not found");
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, loggedInUser.Username),
new Claim(ClaimTypes.Email, loggedInUser.EmailAddress),
new Claim(ClaimTypes.GivenName, loggedInUser.GivenName),
new Claim(ClaimTypes.Surname, loggedInUser.Surname),
new Claim(ClaimTypes.Role, loggedInUser.Role)
};
var token = new JwtSecurityToken
(
issuer: builder.Configuration["Jwt:Issuer"],
audience: builder.Configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddDays(60),
notBefore: DateTime.UtcNow,
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
SecurityAlgorithms.HmacSha256)
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return Results.Ok(tokenString);
}
return Results.BadRequest("Invalid user credentials");
}
}
app.UseCors();
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseAuthentication();
app.UseMiddleware<GlobalExceptionHandlingMiddleware>(); /* IMiddleware approach */
app.MapCarter();
app.MapControllers();
app.Run();