* Added Authorization which is not working

This commit is contained in:
2025-02-23 21:19:04 +01:00
parent 6774311433
commit 5bcf406465
29 changed files with 407 additions and 210 deletions

View File

@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SytelineSaAppEfDataModel.Dtos;
using SytelineSaAppEfDataModel.Services;

View File

@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SytelineSaAppEfDataModel.Dtos;
using SytelineSaAppEfDataModel.Services;

View File

@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SytelineSaAppEfDataModel.Dtos;
using SytelineSaAppEfDataModel.Services;
@@ -6,6 +7,7 @@ namespace FaKrosnoApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class ErrorLogController(IErrorLogService service) : Controller
{
[HttpGet]

View File

@@ -1,18 +0,0 @@
using FaKrosnoEfDataModel.Dtos;
using FaKrosnoEfDataModel.Services;
using Microsoft.AspNetCore.Mvc;
namespace FaKrosnoApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ScheduleOrderDetailsController(IScheduleOrderDetailsService service) : Controller
{
[HttpGet("order/{scheduleOrderId:int}")]
public async Task<ActionResult<IEnumerable<ScheduleOrderDto>>> GetByScheduleOrderId(int scheduleOrderId)
{
IEnumerable<ScheduleOrderDetailDto>? scheduleOrderDetails = await service.GetScheduleOrderDetailsAsync(scheduleOrderId);
return Ok(scheduleOrderDetails);
}
}
}

View File

@@ -1,6 +1,4 @@
using AutoMapper;
using FaKrosnoEfDataModel;
using FaKrosnoEfDataModel.Dtos;
using FaKrosnoEfDataModel.Dtos;
using FaKrosnoEfDataModel.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -9,7 +7,6 @@ namespace FaKrosnoApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
//[Authorize]
public class ScheduleOrdersController(IScheduleOrderService service) : Controller
{
[HttpGet]

View File

@@ -1,5 +1,9 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using FaKrosnoApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using OrdersManagementDataModel.Dtos;
using OrdersManagementDataModel.Services;
@@ -7,7 +11,7 @@ namespace FaKrosnoApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class UsersController(IUserService service) : Controller
public class UsersController(IUserService service, IConfiguration configuration) : Controller
{
[HttpGet]
public async Task<ActionResult<IEnumerable<UserDto>>> GetAll()
@@ -30,51 +34,41 @@ public class UsersController(IUserService service) : Controller
return user != null ? Ok(user) : NotFound();
}
[HttpPost("authenticate")]
public async Task<IActionResult> Authenticate([FromBody] AuthenticateRequestModel? request)
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] AuthenticateRequestModel loginDto)
{
if (request == null || string.IsNullOrEmpty(request.Login) || string.IsNullOrEmpty(request.Password))
{
return BadRequest(new { message = "Login i hasło są wymagane" });
}
var user = await service.GetByUsername(request.Login);
var x = BCrypt.Net.BCrypt.Verify(request.Password, user?.PasswordHash);
// Sprawdź poprawność użytkownika (np. w bazie danych)
var user = await service.GetByUsername(loginDto.Login);
if (user == null || !BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
if(user == null || !BCrypt.Net.BCrypt.Verify(loginDto.Password, user.PasswordHash))
{
return Unauthorized(new { message = "Nieprawidłowy login lub hasło" });
return Unauthorized("Nieprawidłowa nazwa użytkownika lub hasło.");
}
var userDto = new UserDto
var claims = new[]
{
Id = user.Id,
Login = user.Login,
IsTemporaryPassword = user.IsTemporaryPassword,
IsActive = user.IsActive,
ActiveFrom = user.ActiveFrom,
ActiveTo = user.ActiveTo,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
CreatedDate = user.CreatedDate,
LastLoginDate = user.LastLoginDate,
FailedLoginAttempts = user.FailedLoginAttempts,
IsLocked = user.IsLocked,
LockoutEndDate = user.LockoutEndDate,
RowPointer = user.RowPointer
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Login),
};
user.LastLoginDate = DateTime.Now;
user.FailedLoginAttempts = 0;
await service.Login(user);
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
return Ok(userDto);
var token = new JwtSecurityToken(
issuer: configuration["Jwt:Issuer"],
audience: configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddHours(1), // Token ważny przez 1 godzinę
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expires = token.ValidTo
});
}
[HttpPost]
public async Task<ActionResult<UserDto>> Add([FromBody] UserDto user)
{

View File

@@ -12,6 +12,8 @@ using OrdersManagementDataModel;
using OrdersManagementDataModel.Services;
using SytelineSaAppEfDataModel;
using SytelineSaAppEfDataModel.Services;
using NSwag;
using NSwag.Generation.Processors.Security;
using FaKrosnoMappingProfile = FaKrosnoEfDataModel.MappingProfile;
using SytelineSaAppMappingProfile = SytelineSaAppEfDataModel.MappingProfile;
using OrdersManagementMappingProfile = OrdersManagementDataModel.MappingProfile;
@@ -30,12 +32,43 @@ builder.Services.Configure<JobSettingsModel>(builder.Configuration.GetSection("J
builder.WebHost.UseUrls("http://*:5001");
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? string.Empty))
};
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
// Konfiguracja NSwag z obsługą Bearer Token
builder.Services.AddOpenApiDocument(config =>
{
config.Title = "FaKrosnoApi";
config.Version = "v1";
// Dodaj definicję zabezpieczeń Bearer Token
config.AddSecurity("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = OpenApiSecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = OpenApiSecurityApiKeyLocation.Header,
Description = "Wprowadź token JWT w formacie: Bearer {token}"
});
// Zastosuj zabezpieczenia globalnie
config.OperationProcessors.Add(new OperationSecurityScopeProcessor("Bearer"));
});
builder.Services.AddHangfire(config => config
@@ -52,29 +85,9 @@ builder.Services.AddHangfire(config => config
}));
builder.Services.AddHangfireServer();
// Configure AutoMapper
builder.Services.AddAutoMapper(typeof(FaKrosnoMappingProfile), typeof(SytelineSaAppMappingProfile),
typeof(OrdersManagementMappingProfile));
// Configure JWT Authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
builder.Services.AddScoped<IScheduleOrderService, ScheduleOrderService>();
builder.Services.AddScoped<IScheduleOrderDetailsService, ScheduleOrderDetailsService>();
builder.Services.AddScoped<IEdiCustomerOrderService, EdiCustomerOrderService>();
@@ -104,11 +117,4 @@ app.MapControllers();
app.UseHangfireDashboard();
// var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
// using (var scope = scopeFactory.CreateScope())
// {
// var scheduledJob = scope.ServiceProvider.GetRequiredService<IScheduleJobService>();
// scheduledJob.Start();
// }
app.Run();
app.Run();

View File

@@ -1,7 +1,7 @@
{
"ConnectionStrings": {
"FaKrosnoConnection": "Server=192.168.0.7;Database=fakrosno;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true",
"SytelineSaAppConnection": "Server=192.168.0.7;Database=SL_PROD_SA_APP;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true",
"FaKrosnoConnection": "Server=192.168.0.7;Database=fakrosnotest;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true",
"SytelineSaAppConnection": "Server=192.168.0.7;Database=SL_PRODTEST_SA_APP;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true",
"OrdersManagementConnection": "Server=192.168.0.7;Database=OrdersManagement;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true"
},
"Logging": {
@@ -11,7 +11,7 @@
}
},
"Jwt": {
"Key": "ThisIsASecretKeyForJwt",
"Key": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6A7B8C9D0E1F",
"Issuer": "FaKrosnoApi",
"Audience": "FaKrosnoClient"
},