-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
87 lines (60 loc) · 2.3 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
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.IdentityModel.Tokens;
// Here we define how tokens will be.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
string key = "lkjh3k4jh3k4jh32049i32-0e9-f0ewifledkjhflewkjhrkejwhr";
builder.Services.AddAuthentication("Bearer").AddJwtBearer( opt =>
{
var signatureKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var signatureCredential = new SigningCredentials(signatureKey, SecurityAlgorithms.HmacSha256Signature);
opt.RequireHttpsMetadata = false;
opt.TokenValidationParameters = new TokenValidationParameters()
{
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKey = signatureKey,
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Get Endpoint without no Authorizatio
app.MapGet("/", () => $"Hello World!!");
// Get Endpoint -- you need auth first.
app.MapGet("/hello", (ClaimsPrincipal user) => $"Hello {user.Identity?.Name}").RequireAuthorization();
// The Auth endpoint ;)
app.MapGet("/login/{user}/{pass}", (string user, string pass) =>
{
if ( user == "admin" && pass == "1234")
{
var tokenHandler = new JwtSecurityTokenHandler();
var byteKey = Encoding.UTF8.GetBytes(key);
var Tokendes = new SecurityTokenDescriptor
{
Subject = new System.Security.Claims.ClaimsIdentity(new Claim[]
{
new Claim ( ClaimTypes.Name, user),
}),
Expires = DateTime.UtcNow.AddMonths(1),
SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(byteKey),
SecurityAlgorithms.HmacSha256Signature)
};
// Here we create the token based on the prevoius params.
var token = tokenHandler.CreateToken(Tokendes);
return tokenHandler.WriteToken(token);
}
else
{
return "Invalid User or Password!.";
}
});
app.Run();