-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program.cs
65 lines (52 loc) · 1.98 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
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using UserAuthMinimalApi.Models;
using UserAuthMinimalApi.Repositories;
using UserAuthMinimalApi.Services;
using UserAuthMinimalApi.Settings;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<TokenService>();
var secretKey = ApiSettings.GenerateSecretByte();
builder.Services.AddAuthentication(config =>
{
config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(config =>
{
config.RequireHttpsMetadata = false;
config.SaveToken = true;
config.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(secretKey),
ValidateIssuer = false,
ValidateAudience = false
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("manager", policy => policy.RequireRole("manager"));
options.AddPolicy("operator", policy => policy.RequireRole("operator"));
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapPost("/login", (User userModel, TokenService service) =>
{
var user = UserRepository.Find(userModel.Username, userModel.Password);
if (user is null)
return Results.NotFound(new { message = "Invalid username or password" });
var token = service.GenerateToken(user);
user.Password = string.Empty;
return Results.Ok(new { user = user, token = token });
});
app.MapGet("/operator", (ClaimsPrincipal user) =>
{
Results.Ok(new { message = $"Authenticated as { user?.Identity?.Name }" });
}).RequireAuthorization("Operator");
app.MapGet("/manager", (ClaimsPrincipal user) =>
{
Results.Ok(new { message = $"Authenticated as { user?.Identity?.Name }" });
}).RequireAuthorization("Manager");
app.Run();