-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-jwt-tokens.cs
More file actions
executable file
·45 lines (41 loc) · 1.46 KB
/
auth-jwt-tokens.cs
File metadata and controls
executable file
·45 lines (41 loc) · 1.46 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
// Projekt.csproj
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.2"/>
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0"/>
// Generování tokenu včetně claimů
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("asdfghjklasdfghjkl");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "username"),
new Claim(ClaimTypes.Role, "admin")
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return new TokenInfo()
{
Token = tokenHandler.WriteToken(token),
Expires = token.ValidTo
};
// WebApplicationBuilder (builder.Services)
Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
var key = Encoding.ASCII.GetBytes("asdfghjklasdfghjkl");
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});