-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
67 lines (58 loc) · 1.75 KB
/
Program.cs
File metadata and controls
67 lines (58 loc) · 1.75 KB
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
using System.Security.Claims;
using System.Text;
using JwtAspNet;
using JwtAspNet.Extensios;
using JwtAspNet.Model;
using JwtAspNet.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<TokenService>();
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.PrivateString))
};
});
builder.Services.AddAuthorization(x =>
{
x.AddPolicy("admin", policy => policy.RequireRole("admin"));
x.AddPolicy("development", policy => policy.RequireRole("development"));
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/login", (TokenService service) =>
{
var user = new User(
Id: 1,
Name: "John Doe",
Image: "https://avatars.githubusercontent.com/u/19608973?v=4",
Email: "useremail@gmail.com",
Password: "123456",
Roles: new string[] { "admin", "user" }
);
return service.Create(user);
});
app.MapGet("/restrito", (TokenService service, ClaimsPrincipal user) =>
{
return new
{
Id = user.GetId(),
Login = user.GetLogin(),
Name = user.GetName(),
Email = user.GetEmail(),
Image = user.GetImage()
};
}).RequireAuthorization("admin");
app.Run();