Added authentication and authorization, updated dependency injections, removed hard-coded connection string

This commit is contained in:
2024-08-17 16:28:35 +03:00
parent 026a104131
commit 7cbe3d9698
44 changed files with 419 additions and 49 deletions

View File

@@ -0,0 +1,24 @@
using System.IdentityModel.Tokens.Jwt;
using ApplicationLayer.AuthServices.NeededServices;
using ApplicationLayer.GeneralNeededServices;
using Microsoft.Extensions.DependencyInjection;
namespace Infrastructure.Auth
{
public static class ServiceCollectionsExtensions
{
public static IServiceCollection AddTokenGenerator(this IServiceCollection services, TokenGeneratorOptions options)
{
services.AddSingleton<JwtSecurityTokenHandler>();
services.AddSingleton<ITokenGenerator, TokenGenerator>(provider =>
{
var tokenHandler = provider.GetRequiredService<JwtSecurityTokenHandler>();
var dateTimeProvider = provider.GetRequiredService<IDateTimeProvider>();
return new TokenGenerator(options, tokenHandler, dateTimeProvider);
});
return services;
}
}
}

View File

@@ -0,0 +1,30 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using ApplicationLayer.AuthServices.NeededServices;
using ApplicationLayer.GeneralNeededServices;
using Domains.Users;
namespace Infrastructure.Auth
{
public class TokenGenerator(TokenGeneratorOptions options, JwtSecurityTokenHandler tokenHandler, IDateTimeProvider dateTimeProvider)
: ITokenGenerator
{
public string CreateToken(User user)
{
var claims = new List<Claim>
{
new(ClaimTypes.Role, user.Role.ToString()),
new(ClaimTypes.Email, user.Email)
};
var token = new JwtSecurityToken(
issuer: options.Issuer,
audience: options.Audience,
expires: dateTimeProvider.Now().Add(options.ValidTime),
signingCredentials: options.Credentials,
claims: claims);
return tokenHandler.WriteToken(token);
}
}
}

View File

@@ -0,0 +1,6 @@
using Microsoft.IdentityModel.Tokens;
namespace Infrastructure.Auth
{
public record TokenGeneratorOptions(string Issuer, string Audience, TimeSpan ValidTime, SigningCredentials Credentials);
}