updated(AuthController): Aktualisiert, um als Platzhalter für auth api in swagger zu funktionieren.

- umbenennen PlaceholderAuthController
This commit is contained in:
Developer 02 2025-03-11 10:17:27 +01:00
parent 17d8373739
commit 753eb18b71
4 changed files with 48 additions and 158 deletions

View File

@ -1,154 +0,0 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using DigitalData.UserManager.Application.Contracts;
using DigitalData.UserManager.Application.DTOs.User;
using Microsoft.AspNetCore.Authorization;
using DigitalData.UserManager.Application;
using DigitalData.Core.Abstractions.Application;
using Microsoft.Extensions.Localization;
using DigitalData.Core.DTO;
using WorkFlow.API.Models;
using WorkFlow.API.Attributes;
namespace WorkFlow.API.Controllers
{
//TODO: implement up-to-date AuthController in UserManager
[APIKeyAuth]
[Route("api/[controller]")]
[ApiController]
public class AuthController(IUserService userService, IDirectorySearchService dirSearchService, IStringLocalizer<Resource> localizer, ILogger<AuthController> logger) : ControllerBase
{
[AllowAnonymous]
[HttpGet("check")]
public IActionResult CheckAuthentication()
{
try
{
return Ok(User.Identity?.IsAuthenticated ?? false);
}
catch(Exception ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
[NonAction]
public async Task<IActionResult> Login(UserReadDto user)
{
// Create claimsIdentity
var claimsIdentity = new ClaimsIdentity(user.ToClaimList(), CookieAuthenticationDefaults.AuthenticationScheme);
// Create authProperties
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
AllowRefresh = true,
ExpiresUtc = DateTime.UtcNow.AddMinutes(60)
};
// Sign in
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return Ok();
}
[AllowAnonymous]
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] Login login)
{
try
{
return dirSearchService.ValidateCredentials(login.Username, login.Password)
? await userService.ReadByUsernameAsync(login.Username).ThenAsync(
SuccessAsync: Login,
Fail: IActionResult (msg, ntc) =>
{
logger.LogNotice(ntc);
logger.LogError("User could not be found, although verified by directory-search-service. It needs to be imported by UserManager. User name is {username}.", login.Username);
return StatusCode(StatusCodes.Status500InternalServerError);
})
: Unauthorized(localizer[WFKey.UserNotFoundOrWrongPassword].Value);
}
catch(Exception ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
[AllowAnonymous]
[HttpPost("login/{id}")]
public async Task<IActionResult> LoginById([FromRoute] int id, [FromQuery] string password)
{
try
{
return await userService.ReadByIdAsync(id).ThenAsync(
SuccessAsync: async user
=> dirSearchService.ValidateCredentials(user.Username, password)
? await Login(user)
: Unauthorized(localizer[WFKey.WrongPassword].Value),
Fail: (msg, ntc) =>
{
if (ntc.HasFlag(Flag.NotFound))
return Unauthorized(Key.UserNotFound);
logger.LogNotice(ntc);
return StatusCode(StatusCodes.Status500InternalServerError);
});
}
catch (Exception ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
[Authorize]
[HttpGet("user")]
public async Task<IActionResult> GetUserWithClaims()
{
try
{
// Extract the username from the Name claim.
string? username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
if (string.IsNullOrEmpty(username))
return Unauthorized();
return await userService.ReadByUsernameAsync(username)
.ThenAsync(Ok, IActionResult (m, n) =>
{
logger.LogNotice(n);
return NotFound(Result.Fail().Message(localizer[Key.UserNotFound].Value));
});
}
catch (Exception ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
[Authorize]
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
try
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
catch(Exception ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}
}

View File

@ -0,0 +1,44 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using DigitalData.UserManager.Application.Contracts;
using DigitalData.UserManager.Application.DTOs.User;
using Microsoft.AspNetCore.Authorization;
using DigitalData.UserManager.Application;
using DigitalData.Core.Abstractions.Application;
using WorkFlow.API.Models;
using WorkFlow.API.Attributes;
namespace WorkFlow.API.Controllers
{
//TODO: implement up-to-date AuthController in UserManager
[APIKeyAuth]
[Route("Auth")]
[ApiController]
public class PlaceholderAuthController : ControllerBase
{
[HttpPost("login")]
[AllowAnonymous]
public IActionResult Login([FromForm] Login login)
{
throw new NotImplementedException();
}
[HttpPost("logout")]
public IActionResult Logout()
{
throw new NotImplementedException();
}
[HttpPost]
public IActionResult CreateTokenViaBody([FromBody] Login login, [FromQuery] bool cookie = false)
{
throw new NotImplementedException();
}
[HttpGet("check")]
[Authorize]
public IActionResult Check() => Ok();
}
}

View File

@ -1,4 +1,4 @@
namespace WorkFlow.API.Models namespace WorkFlow.API.Models
{ {
public record Login(string Username, string Password); public record Login(int? UserId, string? Username, string Password);
} }

View File

@ -12,7 +12,7 @@
"http": { "http": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": false,
"launchUrl": "swagger", "launchUrl": "swagger",
"applicationUrl": "http://localhost:5130", "applicationUrl": "http://localhost:5130",
"environmentVariables": { "environmentVariables": {
@ -22,7 +22,7 @@
"https": { "https": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": false,
"launchUrl": "swagger", "launchUrl": "swagger",
"applicationUrl": "https://localhost:7120;http://localhost:5130", "applicationUrl": "https://localhost:7120;http://localhost:5130",
"environmentVariables": { "environmentVariables": {
@ -31,7 +31,7 @@
}, },
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": false,
"launchUrl": "swagger", "launchUrl": "swagger",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"