Fix set-avatar auth flow and API avatar upload stability
All checks were successful
Dotnet build and test / build (pull_request) Successful in 8m5s

This commit is contained in:
Paul Schneider 2026-09-04 19:03:08 +01:00
commit b820348558
Signed by: notazof
GPG key ID: 1DD5D838E5343B06
10 changed files with 115 additions and 117 deletions

View file

@ -94,107 +94,6 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
}
public async Task<IActionResult> SignIn(SignInModel model, [FromForm] string button)
{
if (Request.Method == "POST") // "hGbkk9B94NAae#aG"
{
if (model.Provider == null || model.Provider == "LOCAL")
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.UserName);
var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (user != null)
{
var signin = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true);
// validate username/password against in-memory store
if (signin.Succeeded)
{
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId));
// only set explicit expiration here if user chooses "remember me".
// otherwise we rely upon expiration configured in cookie middleware.
await HttpContext.SignInAsync(user, _roleManager, model.RememberMe, _dbContext);
var authResult = await HttpContext.AuthenticateAsync();
if (!authResult.Succeeded)
{
return this.Unauthorized();
}
String bearer = await HttpContext.GetTokenAsync("Bearer", "Bearer");
HttpContext.Response.Cookies.Append("Bearer", bearer);
if (context != null)
{
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", model.ReturnUrl);
}
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}
// request for a local page
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
else if (string.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect("~/");
}
else
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
}
}
await _events.RaiseAsync(new UserLoginFailureEvent(model.UserName, "invalid credentials", clientId: context?.Client.ClientId));
ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
}
}
else
{
// Note: the "provider" parameter corresponds to the external
// authentication provider choosen by the user agent.
if (string.IsNullOrEmpty(model.Provider))
{
_logger.LogWarning("Provider not specified");
return BadRequest();
}
// Instruct the middleware corresponding to the requested external identity
// provider to redirect the user agent to its own authorization endpoint.
// Note: the authenticationScheme parameter must match the value configured in Startup.cs
// Note: the "returnUrl" parameter corresponds to the endpoint the user agent
// will be redirected to after a successful authentication and not
// the redirect_uri of the requesting client application.
if (string.IsNullOrEmpty(model.ReturnUrl))
{
_logger.LogWarning("ReturnUrl not specified");
return BadRequest();
}
// Note: this still is not the redirect uri given to the third party provider, at building the challenge.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { model.ReturnUrl }, protocol: "https", host: Config.Authority);
var properties = _signInManager.ConfigureExternalAuthenticationProperties(model.Provider, redirectUrl);
// var properties = new AuthenticationProperties{RedirectUri=ReturnUrl};
return new ChallengeResult(model.Provider, properties);
}
}
return View(model);
}
/// <summary>
/// Entry point into the login workflow
/// </summary>

View file

@ -16,6 +16,7 @@ using Yavsc.Services;
using Yavsc.ViewModels.Manage;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Authorization;
using IdentityServer8;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
@ -524,8 +525,45 @@ namespace Yavsc.Controllers
}
[HttpGet]
public IActionResult SetAvatar()
public async Task<IActionResult> SetAvatar(
[FromServices] IdentityServerTools identityServerTools)
{
var currentUser = await GetCurrentUserAsync();
if (currentUser == null)
{
return Challenge();
}
var claims = new List<Claim>
{
new("sub", currentUser.Id),
new("name", currentUser.UserName ?? currentUser.Email ?? currentUser.Id),
new("scope", "api"),
new("aud", "api")
};
// Short-lived token limited to avatar upload from this page.
string avatarAccessToken = string.Empty;
try
{
avatarAccessToken = await identityServerTools.IssueClientJwtAsync(
"postit",
300,
new[] { "api" },
new[] { "api" },
claims);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "IssueClientJwtAsync failed for SetAvatar, trying direct IssueJwtAsync fallback.");
}
if (string.IsNullOrWhiteSpace(avatarAccessToken))
{
avatarAccessToken = await identityServerTools.IssueJwtAsync(300, claims);
}
ViewData["AvatarAccessToken"] = avatarAccessToken;
return View();
}