Middleware 1.0
This commit is contained in:
@@ -7,6 +7,8 @@
|
||||
public string FirstName { get; set; } = null!;
|
||||
public string LastName { get; set; } = null!;
|
||||
public string UserName { get;set; } = null!;
|
||||
public string Password { get; set; }
|
||||
public string Password { get; set; }
|
||||
public string JwtToken { get; set; } = null!;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace WorkFlowCheck.Web.Middleware
|
||||
{
|
||||
public class JwtMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private const string _secretKey = "super_secret_key";
|
||||
|
||||
public JwtMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
var token = context.Request.Cookies["AuthToken"];
|
||||
|
||||
if (!string.IsNullOrEmpty(token) && ValidateToken(token, out var claims))
|
||||
{
|
||||
context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"));
|
||||
}
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
|
||||
private bool ValidateToken(string token, out Claim[] claims)
|
||||
{
|
||||
claims = null;
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.UTF8.GetBytes(_secretKey);
|
||||
|
||||
try
|
||||
{
|
||||
var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(key),
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
ClockSkew = TimeSpan.Zero
|
||||
}, out var validatedToken);
|
||||
|
||||
claims = principal.Claims.ToArray();
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using Microsoft.AspNetCore.Identity.Data;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Newtonsoft.Json;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using WorkFlowCheck.Common.DTO;
|
||||
|
||||
namespace WorkFlowCheck.Web.Middleware
|
||||
{
|
||||
public class JwtService
|
||||
{
|
||||
|
||||
private const string SecretKey = "super_secret_key";
|
||||
public readonly IConfiguration _configuration;
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
public JwtService(HttpClient httpClient,IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_httpClient = httpClient;
|
||||
}
|
||||
|
||||
public async Task<string?> AuthenticateUserAsync(UserDTO userDTO)
|
||||
{
|
||||
var jwtSettings = _configuration.GetSection("Jwt");
|
||||
var secretKey = jwtSettings["SecretKey"];
|
||||
var issuer = jwtSettings["Issuer"];
|
||||
var audience = jwtSettings["Audience"];
|
||||
var tokenLifetime = int.Parse(jwtSettings["TokenLifetimeMinutes"]);
|
||||
|
||||
var response = await Authenticate(userDTO.UserName, userDTO.Password);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.Name, userDTO.UserName),
|
||||
new Claim(ClaimTypes.Role, "User")
|
||||
};
|
||||
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: issuer,
|
||||
audience: audience,
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(tokenLifetime),
|
||||
signingCredentials: creds);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private async Task<ApiResponseDTO<UserDTO>> Authenticate(string username, string password)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Az API végpont meghatározása
|
||||
string endpoint = $"{_httpClient.BaseAddress}api/user/authenticate";
|
||||
|
||||
var userDTO = new UserDTO()
|
||||
{
|
||||
Email = "",
|
||||
FirstName = "",
|
||||
LastName = "",
|
||||
Id = 0,
|
||||
UserName = username,
|
||||
Password = password,
|
||||
};
|
||||
|
||||
// HTTP POST kérés küldése
|
||||
|
||||
using (HttpResponseMessage httpResponseMessage = await _httpClient.PostAsJsonAsync(endpoint, userDTO))
|
||||
{
|
||||
httpResponseMessage.EnsureSuccessStatusCode();
|
||||
|
||||
var jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
|
||||
var response = JsonConvert.DeserializeObject<ApiResponseDTO<UserDTO>>(jsonString);
|
||||
|
||||
return response ?? new ApiResponseDTO<UserDTO>
|
||||
{
|
||||
IsSuccess = false,
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Hiba visszaadása
|
||||
return new ApiResponseDTO<UserDTO>
|
||||
{
|
||||
IsSuccess = false
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Serilog;
|
||||
using System.Text;
|
||||
using WorkFlowCheck.Common.DTO;
|
||||
using WorkFlowCheck.Web.Middleware;
|
||||
using WorkFlowCheck.Web.Services;
|
||||
using WorkFlowCheck.Web.Services.Interfaces;
|
||||
|
||||
@@ -17,9 +24,26 @@ builder.Services.AddScoped<IBaseStockService, BaseStockService>();
|
||||
builder.Host.UseSerilog();
|
||||
// Add services to the container.
|
||||
builder.Services.AddRazorPages();
|
||||
builder.Services.AddSingleton<JwtService>();
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.RequireHttpsMetadata = true;
|
||||
options.SaveToken = true;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = "https://auth.example.com",
|
||||
ValidAudience = "https://mywebapp.com",
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("super_secret_key"))
|
||||
};
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseMiddleware<JwtMiddleware>();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
@@ -34,8 +58,25 @@ app.UseStaticFiles();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapPost("/login", async ([FromBody] UserDTO userDTO, JwtService jwtService, HttpContext httpContext) =>
|
||||
{
|
||||
var token = await jwtService.AuthenticateUserAsync(userDTO);
|
||||
if (token is null) return Results.Unauthorized();
|
||||
|
||||
httpContext.Response.Cookies.Append("AuthToken", token, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict
|
||||
});
|
||||
return Results.Ok(new { Token = token });
|
||||
});
|
||||
|
||||
app.MapGet("/secure-data", [Authorize] () => "This is protected data");
|
||||
|
||||
app.MapRazorPages();
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -16,12 +16,14 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="jquery" Version="3.7.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.14" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.11" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.6.1" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\WorkFlowCheck.Common\WorkFlowCheck.Common.csproj" />
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
{
|
||||
"ApiBaseUrl": "https://wfcapi.nuvolar.hu/",
|
||||
"ApiKey": "RUJeLSpSMzVASUdaRCEzUyYxRSE0VyFISFRSJC0zRzhLM1hCSDU=",
|
||||
"Jwt": {
|
||||
"SecretKey": "super_secret_key",
|
||||
"Issuer": "https://wfcapi.nuvolar.hu/",
|
||||
"Audience": "https://mywebapp.com",
|
||||
"TokenLifetimeMinutes": 30
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
|
||||
Reference in New Issue
Block a user