mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 20:40:07 +01:00
feat: offload jwt generation to guhf, move auth code to new controller
This commit is contained in:
41
Controllers/AuthController.cs
Normal file
41
Controllers/AuthController.cs
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using QuotifyBE.Data;
|
||||||
|
using QuotifyBE.DTOs;
|
||||||
|
|
||||||
|
namespace QuotifyBE.Controllers;
|
||||||
|
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/v1/auth")]
|
||||||
|
public class AuthController : ControllerBase
|
||||||
|
{
|
||||||
|
|
||||||
|
private readonly IConfiguration _appsettings;
|
||||||
|
private readonly ApplicationDbContext _db;
|
||||||
|
|
||||||
|
public AuthController(IConfiguration appsettings, ApplicationDbContext db)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_appsettings = appsettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("login")]
|
||||||
|
public IActionResult Login([FromBody] UserLoginDTO user, GeneralUseHelpers guhf)
|
||||||
|
{
|
||||||
|
if (user.Email == "admin" && user.Password == "password")
|
||||||
|
{
|
||||||
|
var token = guhf.GenerateJwtToken(user.Email, _appsettings);
|
||||||
|
return Ok(new { token });
|
||||||
|
}
|
||||||
|
return Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("some_values")]
|
||||||
|
[Authorize]
|
||||||
|
public IActionResult GetValues()
|
||||||
|
{
|
||||||
|
return Ok(new string[] { "value1", "value2" });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
34
Controllers/GeneralUseHelperFunctions.cs
Normal file
34
Controllers/GeneralUseHelperFunctions.cs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace QuotifyBE.Controllers;
|
||||||
|
|
||||||
|
public class GeneralUseHelpers
|
||||||
|
{
|
||||||
|
public string GenerateJwtToken(string username, IConfiguration appsettings)
|
||||||
|
{
|
||||||
|
var claims = new[]
|
||||||
|
{
|
||||||
|
new Claim(JwtRegisteredClaimNames.Sub, username),
|
||||||
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
||||||
|
};
|
||||||
|
|
||||||
|
var key = new SymmetricSecurityKey(
|
||||||
|
Encoding.UTF8.GetBytes(appsettings["JwtSecret"]!)
|
||||||
|
// won't be null here - otherwise Program.cs wouldn't start
|
||||||
|
);
|
||||||
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||||
|
|
||||||
|
var token = new JwtSecurityToken(
|
||||||
|
issuer: appsettings["DomainName"]!,
|
||||||
|
audience: appsettings["DomainName"]!,
|
||||||
|
claims: claims,
|
||||||
|
expires: DateTime.Now.AddDays(7),
|
||||||
|
signingCredentials: creds
|
||||||
|
);
|
||||||
|
|
||||||
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Microsoft.IdentityModel.Tokens;
|
|
||||||
using QuotifyBE.Controllers;
|
|
||||||
using QuotifyBE.DTOs;
|
|
||||||
using System.IdentityModel.Tokens.Jwt;
|
|
||||||
using System.Security.Claims;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace QuotifyBE.Controllers
|
|
||||||
{
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Route("[controller]")]
|
|
||||||
public class WeatherForecastController : ControllerBase
|
|
||||||
{
|
|
||||||
|
|
||||||
private static readonly string[] Summaries = new[]
|
|
||||||
{
|
|
||||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
|
||||||
};
|
|
||||||
|
|
||||||
private readonly ILogger<WeatherForecastController> _logger;
|
|
||||||
private readonly IConfiguration _appsettings;
|
|
||||||
|
|
||||||
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration appsettings)
|
|
||||||
{
|
|
||||||
_logger = logger;
|
|
||||||
_appsettings = appsettings;
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpGet(Name = "GetWeatherForecast")]
|
|
||||||
public IEnumerable<WeatherForecast> Get()
|
|
||||||
{
|
|
||||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
|
||||||
{
|
|
||||||
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
|
||||||
TemperatureC = Random.Shared.Next(-20, 55),
|
|
||||||
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
|
|
||||||
})
|
|
||||||
.ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpPost("login")]
|
|
||||||
public IActionResult Login([FromBody] UserLoginDTO user)
|
|
||||||
{
|
|
||||||
if (user.Email == "admin" && user.Password == "password")
|
|
||||||
{
|
|
||||||
var token = GenerateJwtToken(user.Email);
|
|
||||||
return Ok(new { token });
|
|
||||||
}
|
|
||||||
return Unauthorized();
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpGet("some_values")]
|
|
||||||
[Authorize]
|
|
||||||
public IActionResult GetValues()
|
|
||||||
{
|
|
||||||
return Ok(new string[] { "value1", "value2" });
|
|
||||||
}
|
|
||||||
|
|
||||||
private string GenerateJwtToken(string username)
|
|
||||||
{
|
|
||||||
var claims = new[]
|
|
||||||
{
|
|
||||||
new Claim(JwtRegisteredClaimNames.Sub, username),
|
|
||||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
|
||||||
};
|
|
||||||
|
|
||||||
var key = new SymmetricSecurityKey(
|
|
||||||
Encoding.UTF8.GetBytes(_appsettings["JwtSecret"]!)
|
|
||||||
// won't be null here - otherwise Program.cs wouldn't start
|
|
||||||
);
|
|
||||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
||||||
|
|
||||||
var token = new JwtSecurityToken(
|
|
||||||
issuer: _appsettings["DomainName"]!,
|
|
||||||
audience: _appsettings["DomainName"]!,
|
|
||||||
claims: claims,
|
|
||||||
expires: DateTime.Now.AddDays(7),
|
|
||||||
signingCredentials: creds
|
|
||||||
);
|
|
||||||
|
|
||||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using QuotifyBE.Controllers;
|
||||||
using QuotifyBE.Data;
|
using QuotifyBE.Data;
|
||||||
using QuotifyBE.Entities;
|
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
// Configure Database Conecction
|
// Configure Database Connection
|
||||||
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
|
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
|
||||||
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
||||||
options.UseNpgsql(connectionString));
|
options.UseNpgsql(connectionString));
|
||||||
@@ -40,6 +40,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
|||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
builder.Services.AddAuthorization();
|
builder.Services.AddAuthorization();
|
||||||
builder.Services.AddSingleton(builder.Configuration);
|
builder.Services.AddSingleton(builder.Configuration);
|
||||||
|
builder.Services.AddScoped<GeneralUseHelpers>();
|
||||||
|
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||||
|
|||||||
Reference in New Issue
Block a user