api e token con ck in db
This commit is contained in:
1 parent
a172f05269
commit
2db9525570
18 files changed
+570
-161
No files matched your search
@@ -0,0 +1,32 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace uWine.Api.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("/[controller]")]
|
||||
public class TestController : Controller
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public TestController(IConfiguration configuration) {
|
||||
_configuration = configuration;
|
||||
}
|
||||
[HttpGet("cklogin")]
|
||||
public IActionResult test()
|
||||
{
|
||||
try
|
||||
{
|
||||
var TUserId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
var userId = User.FindFirst("userId").Value;
|
||||
var role = User.FindFirst(ClaimTypes.Role)?.Value;
|
||||
return Ok(new { userId, TUserId, role });
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Unauthorized("\"title\": \"Unauthorized\"");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,83 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using uWine.Core.Domain.Entities;
|
||||
using uWine.Core.Infrastructure.Services;
|
||||
|
||||
namespace uWine.Api.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("/login/")]
|
||||
[Route("/[controller]")]
|
||||
public class UserController : Controller
|
||||
{
|
||||
public IActionResult Index()
|
||||
private readonly IConfiguration _configuration;
|
||||
readonly AuthenticationService _authenticationService;
|
||||
public UserController(IConfiguration configuration, AuthenticationService authenticationService)
|
||||
{
|
||||
return View();
|
||||
_configuration = configuration;
|
||||
_authenticationService = authenticationService;
|
||||
}
|
||||
//public IActionResult Index()
|
||||
//{
|
||||
// return View();
|
||||
//}
|
||||
|
||||
[HttpGet("login")]
|
||||
public IActionResult LoginWithBasic()
|
||||
{
|
||||
if (!Request.Headers.ContainsKey("Authorization"))
|
||||
return Unauthorized("Authorization header missing");
|
||||
|
||||
var authHeader = Request.Headers["Authorization"].ToString();
|
||||
|
||||
if (!authHeader.StartsWith("Basic "))
|
||||
return Unauthorized("Invalid auth scheme");
|
||||
|
||||
var encodedCredentials = authHeader.Substring("Basic ".Length).Trim();
|
||||
var decodedBytes = Convert.FromBase64String(encodedCredentials);
|
||||
var decodedCredentials = Encoding.UTF8.GetString(decodedBytes);
|
||||
|
||||
var parts = decodedCredentials.Split(':', 2);
|
||||
if (parts.Length != 2)
|
||||
return Unauthorized("Invalid credentials format");
|
||||
var user = new User { Username = parts[0], Password = parts[1] };
|
||||
var auth = _authenticationService.IsAuthenticated(user);
|
||||
|
||||
// 🔐 Autenticazione fittizia (da sostituire con verifica DB)
|
||||
if (!auth)
|
||||
return Unauthorized("Credenziali non valide");
|
||||
|
||||
user = _authenticationService.User(user);
|
||||
|
||||
var token = GenerateJwtToken(user);
|
||||
return Ok(new { access_token = token });
|
||||
}
|
||||
|
||||
|
||||
private string GenerateJwtToken(User user)
|
||||
{
|
||||
var jwtSettings = _configuration.GetSection("JwtSettings");
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim("userId", user.Id.ToString()),
|
||||
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
|
||||
new Claim(ClaimTypes.Role, user.Role.Id.ToString())
|
||||
};
|
||||
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Secret"]));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: jwtSettings["Issuer"],
|
||||
audience: jwtSettings["Audience"],
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(jwtSettings["ExpiresInMinutes"])),
|
||||
signingCredentials: creds
|
||||
);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-1
@@ -1,4 +1,11 @@
|
||||
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
using uWine.Core.Domain.Repositories;
|
||||
using uWine.Core.Infrastructure.Repository;
|
||||
using uWine.Core.Infrastructure.Services;
|
||||
|
||||
namespace uWine.Api
|
||||
{
|
||||
public class Program
|
||||
@@ -7,13 +14,35 @@ namespace uWine.Api
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtSettings["Issuer"],
|
||||
ValidAudience = jwtSettings["Audience"],
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Secret"]))
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddTransient<IAuthenticationRepository, MariaDbAuthenticationRepository>();
|
||||
builder.Services.AddTransient<AuthenticationService>();
|
||||
//builder.Services.AddSingleton<MariaDbServerRepository>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
|
||||
@@ -5,5 +5,18 @@
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"AllowedHosts": "*",
|
||||
"JwtSettings": {
|
||||
"Secret": "questa-chiave-deve-essere-lunga-e-sicura",
|
||||
"Issuer": "IlTuoPortaleAPI",
|
||||
"Audience": "IlTuoClientApp",
|
||||
"ExpiresInMinutes": 60
|
||||
},
|
||||
"db": {
|
||||
"mariaDbServer": "192.168.0.7",
|
||||
"mariaDbSchema": "uvineyard",
|
||||
"mariaDbUser": "administrator",
|
||||
"mariaDbPassword": "123456",
|
||||
"mariaDbPoolSize": 100
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,13 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.18" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\uWine.Core.Domain\uWine.Core.Domain.csproj" />
|
||||
<ProjectReference Include="..\uWine.Core.Infrastructure\uWine.Core.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in new issue
Block a user