-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
221 lines (180 loc) · 6.57 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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.ComponentModel.DataAnnotations;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<TodoDB>(options =>
{
options.UseInMemoryDatabase("Todo");
});
builder.Services.AddSingleton<ITokenService>(new TokenService());
builder.Services.AddSingleton<IUserRepositoryService>(new UserRepositoryService());
builder.Services.AddAuthorization();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:key"]))
};
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
var securitySchema = new OpenApiSecurityScheme
{
Name = "JWT ÀÎÁõ",
Description = "JWT Bearer tokenÀ» ÀÔ·ÂÇϼ¼¿ä",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Reference = new OpenApiReference
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};
c.AddSecurityDefinition(securitySchema.Reference.Id, securitySchema);
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{ securitySchema, new string[] { } }
});
});
builder.Services.AddMvc();
var app = builder.Build();
//app.MapGet("/", () => "Called Get API");
//app.MapPost("/api/post", () => "Called Post API");
//app.MapPut("/api/put", () => "Called Put API");
//app.MapDelete("/api/del", () => "Called Delete API");
app.MapGet("/todo", async (TodoDB db) => await db.TodoList.ToListAsync())
.Produces<List<Todo>>(StatusCodes.Status200OK)
.WithName("GetAllTodoList").WithTags("Getters");
app.MapPost("/todo", async ([FromBody] Todo todo, [FromServices] TodoDB db, HttpResponse response) =>
{
db.TodoList.Add(todo);
await db.SaveChangesAsync();
response.StatusCode = 200;
response.Headers.Location = $"todo/{todo.Id}";
return Results.Created($"todo/{todo.Id}", todo);
}).Accepts<Todo>("application/json")
.Produces<Todo>(StatusCodes.Status201Created);
app.MapPut("/todo", async (int todoId, string title, [FromServices] TodoDB db, HttpResponse response) =>
{
var todo = db.TodoList.SingleOrDefault(x => x.Id == todoId);
if (todo == null) return Results.NotFound();
todo.Title = title;
await db.SaveChangesAsync();
return Results.Created("/todo", todo);
});
app.MapGet("/todo/{id}", async (TodoDB db, int id) =>
await db.TodoList.SingleOrDefaultAsync(x => x.Id == id) is Todo todo ? Results.Ok(todo) : Results.NotFound());
app.MapGet("/todo/search/{query}", (string query, TodoDB db) =>
{
var todoList = db.TodoList.Where(x => x.Title.ToLower().Contains(query.ToLower())).ToList();
return todoList.Count > 0 ? Results.Ok(todoList) : Results.NotFound();
}).Produces<List<Todo>>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound);
app.MapPost("/login", [AllowAnonymous] async ([FromBody] UserModel userModel, ITokenService tokenService, IUserRepositoryService userRepositoryService, HttpResponse response) =>
{
var userDto = userRepositoryService.GetUser(userModel);
if (userDto == null)
{
response.StatusCode = 401;
return;
}
var issuer = builder.Configuration["Jwt:Issuer"];
var audience = builder.Configuration["Jwt:Audience"];
var key = builder.Configuration["Jwt:Key"];
var token = tokenService.BuildToken(key, issuer, audience, userDto);
await response.WriteAsJsonAsync(new { token = token});
return;
}).Produces(StatusCodes.Status200OK).WithName("Login").WithTags("Accounts");
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id}"
);
endpoints.MapControllerRoute(
"Root",
"{action}",
new { controller = "Home", action = "Index"}
);
});
app.UseSwagger();
app.UseSwaggerUI();
app.Run();
public interface ITokenService
{
string BuildToken(string key, string issuer, string audience, User user);
}
public class TokenService : ITokenService
{
private TimeSpan ExpiryDuration = new TimeSpan(0, 30, 0);
public string BuildToken(string key, string issuer, string audience, User user)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())
};
var mySecret = Encoding.UTF8.GetBytes(key);
var securityKey = new SymmetricSecurityKey(mySecret);
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new JwtSecurityToken(issuer, audience, claims,
expires: DateTime.Now.Add(ExpiryDuration), signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
}
}
public record User(string UserName, string Password);
public record UserModel
{
public UserModel(string userName, string password)
{
UserName = userName;
Password = password;
}
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
public interface IUserRepositoryService
{
User? GetUser(UserModel model);
}
public class UserRepositoryService : IUserRepositoryService
{
public List<User> _users = new List<User>()
{
new("admin", "1234")
};
public User? GetUser(UserModel model)
=> _users.FirstOrDefault(x => string.Equals(x.UserName, model.UserName) && string.Equals(x.Password, model.Password));
}
public class Todo
{
[Key]
public int Id { get; set; }
public string? Title { get; set; }
public bool Checked { get; set; }
}
class TodoDB : DbContext
{
public TodoDB(DbContextOptions options) : base(options) { }
public DbSet<Todo> TodoList => Set<Todo>();
}