-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJwt-Swagger.txt
188 lines (139 loc) · 4.98 KB
/
Jwt-Swagger.txt
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using MinimalJwt.Models;
using MinimalJwt.Services;
var builder = WebApplication.CreateBuilder(args);
var _config = builder.Configuration;
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateActor = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = _config["Jwt:Issuer"],
ValidAudience = _config["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]))
};
});
builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer();
//configuration for swagger token authentication
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.AddSingleton<IMovieService, MovieService>();
builder.Services.AddSingleton<IUserService, UserService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapPost("/login", (UserLogin user, IUserService service) => Login(user, service));
IResult Login(UserLogin user, IUserService service)
{
if(!string.IsNullOrEmpty(user.Username) && !string.IsNullOrEmpty(user.Password))
{
var loggedInUser = service.GetUser(user);
if (loggedInUser is null) return Results.NotFound("User not found,register");
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier,loggedInUser.Username),
new Claim(ClaimTypes.Email,loggedInUser.Email),
new Claim(ClaimTypes.GivenName,loggedInUser.Givenname),
new Claim(ClaimTypes.Surname,loggedInUser.Surname),
new Claim(ClaimTypes.Role,loggedInUser.Role),
};
var token = new JwtSecurityToken
(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddDays(15),
notBefore: DateTime.UtcNow
,
signingCredentials: new SigningCredentials
(new SymmetricSecurityKey
(Encoding.UTF8.GetBytes(_config["Jwt:Key"])),
SecurityAlgorithms.HmacSha256)
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return Results.Ok(tokenString);
}
return Results.NotFound();
}
app.MapPost("/create",
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme,Roles = "Admin")]
(Movie movie, IMovieService services) => Create(movie, services));
IResult Create(Movie movie, IMovieService services)
{
var result= services.Create(movie);
return Results.Ok(result);
}
app.MapGet("/get",
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "Admin,Standerd")]
(int Id, IMovieService services) => Get(Id, services));
IResult Get(int id, IMovieService services)
{
var movie= services.Get(id);
if (movie is null) return Results.NotFound("Movie not found");
return Results.Ok(movie);
}
app.MapGet("/list",(IMovieService services) => List(services));
IResult List(IMovieService services)
{
var movies = services.List();
return Results.Ok(movies);
}
app.MapPut("/update",
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "Admin")]
(Movie newmovie, IMovieService services) => Update(newmovie, services));
IResult Update(Movie newmovie, IMovieService services)
{
var updatedMovie=services.Update(newmovie);
if (updatedMovie is null) return Results.NotFound("Movie not found");
return Results.Ok(updatedMovie);
}
app.MapDelete("/delete", (int Id, IMovieService services) => Delete(Id, services));
IResult Delete(int id, IMovieService services)
{
var result= services.Delete(id);
if (!result) return Results.NotFound("Something went wrong");
return Results.Ok(result);
}
app.Run();