feat(AuthController): Erstellt, um Token für Benutzer von UserManager bereitzustellen.

This commit is contained in:
Developer 02
2025-01-15 12:53:51 +01:00
parent 0a3e1566eb
commit a66570bebb
5 changed files with 138 additions and 9 deletions

View File

@@ -0,0 +1,123 @@
using DigitalData.Auth.API.Config;
using DigitalData.Core.Abstractions.Security;
using DigitalData.UserManager.Domain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using DigitalData.UserManager.Application.DTOs.Auth;
using DigitalData.UserManager.Application.Contracts;
using DigitalData.UserManager.Application.DTOs.User;
using DigitalData.Core.Abstractions.Application;
using System.Net;
namespace DigitalData.Auth.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IJwtSignatureHandler<UserReadDto> _userSignatureHandler;
private readonly AuthApiParams _apiParams;
private readonly ICryptoFactory _cryptoFactory;
private readonly ILogger<AuthController> _logger;
private readonly IUserService _userService;
private readonly IDirectorySearchService _dirSearchService;
public AuthController(IJwtSignatureHandler<UserReadDto> userSignatureHandler, IOptions<AuthApiParams> cookieParamsOptions, ICryptoFactory cryptoFactory, ILogger<AuthController> logger, IUserService userService, IDirectorySearchService dirSearchService)
{
_apiParams = cookieParamsOptions.Value;
_userSignatureHandler = userSignatureHandler;
_cryptoFactory = cryptoFactory;
_logger = logger;
_userService = userService;
_dirSearchService = dirSearchService;
}
private async Task<IActionResult> CreateTokenAsync(LogInDto login, string consumerRoute, bool cookie = true)
{
bool isValid = _dirSearchService.ValidateCredentials(login.Username, login.Password);
if (!isValid)
return Unauthorized();
//find the user
var uRes = await _userService.ReadByUsernameAsync(login.Username);
if (!uRes.IsSuccess || uRes.Data is null)
{
return Unauthorized();
}
if (!_apiParams.Consumers.TryGetByRoute(consumerRoute, out var consumer))
return Unauthorized();
_cryptoFactory.TokenDescriptors.TryGet(_apiParams.Issuer, consumer.Audience, out var descriptor);
var token = _userSignatureHandler.WriteToken(uRes.Data, descriptor);
//set cookie
if (cookie)
{
Response.Cookies.Append(_apiParams.CookieName, token, consumer.CookieOptions.Create(lifetime: descriptor.Lifetime));
return Ok();
}
else
return Ok(token);
}
//TODO: Add role depends on group name
[HttpPost("~/{consumerRoute}/login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] LogInDto login, string consumerRoute)
{
try
{
return await CreateTokenAsync(login, consumerRoute, true);
}
catch (Exception ex)
{
_logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
[HttpPost("logout")]
public IActionResult Logout()
{
try
{
Response.Cookies.Delete(_apiParams.CookieName);
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
[HttpPost("{consumerRoute}")]
public async Task<IActionResult> CreateTokenViaBody([FromBody] LogInDto login, [FromRoute] string consumerRoute, [FromQuery] bool cookie = false)
{
try
{
return await CreateTokenAsync(login, consumerRoute, cookie);
}
catch (Exception ex)
{
_logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
[HttpGet("check")]
[Authorize]
public IActionResult Check() => Ok();
}
}