77using System . Net . Http . Headers ;
88using System . Threading . Tasks ;
99using System . Web . Mvc ;
10+ using Microsoft . Build . Framework ;
11+ using Microsoft . Extensions . Logging ;
1012using NuGetGallery . Authentication ;
1113using NuGetGallery . Services . Authentication ;
1214
@@ -32,13 +34,16 @@ public class TokenApiController : AppController
3234
3335 private readonly IFederatedCredentialService _federatedCredentialService ;
3436 private readonly IFederatedCredentialConfiguration _configuration ;
37+ private readonly ILogger < TokenApiController > _logger ;
3538
3639 public TokenApiController (
3740 IFederatedCredentialService federatedCredentialService ,
38- IFederatedCredentialConfiguration configuration )
41+ IFederatedCredentialConfiguration configuration ,
42+ ILogger < TokenApiController > logger )
3943 {
4044 _federatedCredentialService = federatedCredentialService ?? throw new ArgumentNullException ( nameof ( federatedCredentialService ) ) ;
4145 _configuration = configuration ?? throw new ArgumentNullException ( nameof ( configuration ) ) ;
46+ _logger = logger ;
4247 }
4348
4449#pragma warning disable CA3147 // No need to validate Antiforgery Token with API request
@@ -86,6 +91,15 @@ public async Task<ActionResult> CreateToken(CreateTokenRequest request)
8691
8792 var result = await _federatedCredentialService . GenerateApiKeyAsync ( request ! . Username ! , bearerToken ! , Request . Headers ) ;
8893
94+ if ( result . Type == GenerateApiKeyResultType . Created )
95+ {
96+ _logger . LogInformation ( "Token creation request for user {Username} succeeded. API key expires at {Expiration:O}." , request . Username , result . Expires ) ;
97+ }
98+ else
99+ {
100+ _logger . LogWarning ( "Token creation request for user {Username} failed with result type {ResultType}. User message: {UserMessage}" , request . Username , result . Type , result . UserMessage ) ;
101+ }
102+
89103 return result . Type switch
90104 {
91105 GenerateApiKeyResultType . BadRequest => ErrorJson ( HttpStatusCode . BadRequest , result . UserMessage ) ,
@@ -119,7 +133,15 @@ private JsonResult ErrorJson(HttpStatusCode status, string errorMessage)
119133 {
120134 // Show the error message in the HTTP reason phrase (status description) for compatibility with NuGet client error "protocol".
121135 // This, and the response body below, could be formalized with https://github.com/NuGet/NuGetGallery/issues/5818
122- Response . StatusDescription = errorMessage ;
136+ try
137+ {
138+ Response . StatusDescription = errorMessage ;
139+ }
140+ catch
141+ {
142+ // Best effort: setting StatusDescription can fail based on the content of the error message.
143+ _logger . LogWarning ( "Failed to set StatusDescription to '{ErrorMessage}'" , errorMessage ) ;
144+ }
123145
124146 return Json ( status , new { error = errorMessage } ) ;
125147 }
0 commit comments