Добавил авторизацию

This commit is contained in:
2026-06-16 00:59:20 +03:00
parent e55c54e75d
commit 4a4ee24ce7
2 changed files with 22 additions and 1 deletions
@@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore;
using URL_Shortener.DTO; using URL_Shortener.DTO;
using URL_Shortener.Models; using URL_Shortener.Models;
using HashidsNet; using HashidsNet;
using Microsoft.AspNetCore.Authorization;
namespace URL_Shortener.Controllers namespace URL_Shortener.Controllers
{ {
@@ -78,12 +79,15 @@ namespace URL_Shortener.Controllers
} }
[HttpDelete("{id:int}")] [HttpDelete("{id:int}")]
[Authorize]
public async Task<IActionResult> DeleteShortUrlByIdAsync(int id) public async Task<IActionResult> DeleteShortUrlByIdAsync(int id)
{ {
var shortUrl = await _db.ShortUrls.FindAsync(id); var shortUrl = await _db.ShortUrls.FindAsync(id);
if (shortUrl == null) if (shortUrl == null)
return NotFound(); return NotFound();
// TODO: определение пользователя по jwt
_db.ShortUrls.Remove(shortUrl); _db.ShortUrls.Remove(shortUrl);
var clickInfos = _db.ClickInfos.Where(c => c.ShortUrlId == id); var clickInfos = _db.ClickInfos.Where(c => c.ShortUrlId == id);
+18 -1
View File
@@ -1,7 +1,10 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using URL_Shortener; using URL_Shortener;
using URL_Shortener.Services; using URL_Shortener.Services;
using URL_Shortener.Settings; using URL_Shortener.Settings;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -18,7 +21,20 @@ builder.Services.AddSingleton<HashidsNet.Hashids>();
builder.Services.AddScoped<UserService>(); builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<JwtService>(); builder.Services.AddScoped<JwtService>();
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
var authSettings = builder.Configuration.GetSection("AuthSettings");
builder.Services.Configure<AuthSettings>(authSettings);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o => o.TokenValidationParameters = new()
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
authSettings.Get<AuthSettings>().SecretKey))
});
builder.Services.AddDbContext<AppDbContext>(options => builder.Services.AddDbContext<AppDbContext>(options =>
{ {
@@ -47,6 +63,7 @@ using (var scope = app.Services.CreateScope())
//app.UseHttpsRedirection(); //app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapControllers(); app.MapControllers();