add: Keycloak auth & git api client

This commit is contained in:
h z
2025-03-11 11:47:37 +00:00
parent 5718d41102
commit 8b5d4ff5f7
7 changed files with 190 additions and 7 deletions

View File

@@ -7,13 +7,15 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NSwag.MSBuild" Version="14.2.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="RabbitMQ.Client" Version="7.1.1" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.Extensions.Options">
<HintPath>..\..\..\..\.nuget\packages\microsoft.extensions.options\9.0.2\lib\net9.0\Microsoft.Extensions.Options.dll</HintPath>
</Reference>
</ItemGroup>
<Target Name="GenerateNSwagClient" BeforeTargets="Build">
<Exec Command="$(NSwagExe_Net80) run nswag.json" />
</Target>
</Project>

100
nswag.json Normal file
View File

@@ -0,0 +1,100 @@
{
"runtime": "Net80",
"defaultVariables": null,
"documentGenerator": {
"fromDocument": {
"url": "https://git.hangman-lab.top/swagger.v1.json",
"output": null,
"newLineBehavior": "Auto"
}
},
"codeGenerators": {
"openApiToCSharpClient": {
"clientBaseClass": null,
"configurationClass": null,
"generateClientClasses": true,
"suppressClientClassesOutput": false,
"generateClientInterfaces": false,
"suppressClientInterfacesOutput": false,
"clientBaseInterface": null,
"injectHttpClient": true,
"disposeHttpClient": true,
"protectedMethods": [],
"generateExceptionClasses": true,
"exceptionClass": "ApiException",
"wrapDtoExceptions": true,
"useHttpClientCreationMethod": false,
"httpClientType": "System.Net.Http.HttpClient",
"useHttpRequestMessageCreationMethod": false,
"useBaseUrl": true,
"generateBaseUrlProperty": true,
"generateSyncMethods": false,
"generatePrepareRequestAndProcessResponseAsAsyncMethods": false,
"exposeJsonSerializerSettings": false,
"clientClassAccessModifier": "public",
"typeAccessModifier": "public",
"propertySetterAccessModifier": "",
"generateNativeRecords": false,
"generateContractsOutput": false,
"contractsNamespace": null,
"contractsOutputFilePath": null,
"parameterDateTimeFormat": "s",
"parameterDateFormat": "yyyy-MM-dd",
"generateUpdateJsonSerializerSettingsMethod": true,
"useRequestAndResponseSerializationSettings": false,
"serializeTypeInformation": false,
"queryNullValue": "",
"className": "GiteaApiClient",
"operationGenerationMode": "MultipleClientsFromOperationId",
"additionalNamespaceUsages": [],
"additionalContractNamespaceUsages": [],
"generateOptionalParameters": false,
"generateJsonMethods": false,
"enforceFlagEnums": false,
"parameterArrayType": "System.Collections.Generic.IEnumerable",
"parameterDictionaryType": "System.Collections.Generic.IDictionary",
"responseArrayType": "System.Collections.Generic.ICollection",
"responseDictionaryType": "System.Collections.Generic.IDictionary",
"wrapResponses": false,
"wrapResponseMethods": [],
"generateResponseClasses": true,
"responseClass": "SwaggerResponse",
"namespace": "Alchegos.Core.Services.Gitea",
"requiredPropertiesMustBeDefined": true,
"dateType": "System.DateTimeOffset",
"jsonConverters": null,
"anyType": "object",
"dateTimeType": "System.DateTimeOffset",
"timeType": "System.TimeSpan",
"timeSpanType": "System.TimeSpan",
"arrayType": "System.Collections.Generic.ICollection",
"arrayInstanceType": "System.Collections.ObjectModel.Collection",
"dictionaryType": "System.Collections.Generic.IDictionary",
"dictionaryInstanceType": "System.Collections.Generic.Dictionary",
"arrayBaseType": "System.Collections.ObjectModel.Collection",
"dictionaryBaseType": "System.Collections.Generic.Dictionary",
"classStyle": "Poco",
"jsonLibrary": "NewtonsoftJson",
"generateDefaultValues": true,
"generateDataAnnotations": true,
"excludedTypeNames": [],
"excludedParameterNames": [],
"handleReferences": false,
"generateImmutableArrayProperties": false,
"generateImmutableDictionaryProperties": false,
"jsonSerializerSettingsTransformationMethod": null,
"inlineNamedArrays": false,
"inlineNamedDictionaries": false,
"inlineNamedTuples": true,
"inlineNamedAny": false,
"generateDtoTypes": true,
"generateOptionalPropertiesAsNullable": false,
"generateNullableReferenceTypes": false,
"templateDirectory": null,
"serviceHost": null,
"serviceSchemes": null,
"output": "src/Services/Gitea/GiteaApiClient.cs",
"newLineBehavior": "Auto"
}
}
}

View File

@@ -0,0 +1,19 @@
using System.Net;
using Microsoft.Extensions.Options;
namespace Alchegos.Core.Services.Gitea;
public partial class GiteaApiClient
{
private GiteaApiOptions Options;
public GiteaApiClient(HttpClient client, IOptions<GiteaApiOptions> options)
{
_httpClient = client;
Options = options.Value;
BaseUrl = Options.BaseUrl;
_httpClient.DefaultRequestHeaders.Add("Authorization", $"token {Options.Token}");
}
}

View File

@@ -0,0 +1,7 @@
namespace Alchegos.Core.Services.Gitea;
public class GiteaApiOptions
{
public string BaseUrl { get; set; }
public string Token { get; set; }
}

View File

@@ -0,0 +1,6 @@
namespace Alchegos.Core.Services.KeyCloak;
public interface IKeyCloakAuthProvider
{
Task<string> GetTokenAsync();
}

View File

@@ -0,0 +1,11 @@
namespace Alchegos.Core.Services.KeyCloak;
public class KeyCloakAuthOptions
{
public string Authority { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Scopes { get; set; }
}

View File

@@ -0,0 +1,38 @@
using System.Text.Json;
using Microsoft.Extensions.Options;
namespace Alchegos.Core.Services.KeyCloak;
public class KeyCloakAuthProvider : IKeyCloakAuthProvider
{
private KeyCloakAuthOptions Options { get; set; }
private HttpClient Client { get; set; }
public KeyCloakAuthProvider(IOptions<KeyCloakAuthOptions> options, HttpClient client)
{
Options = options.Value;
Client = client;
}
public async Task<string> GetTokenAsync()
{
string tokenEndpoint = $"{Options.Authority}/protocol/openid-connect/token";
Console.WriteLine(tokenEndpoint);
Dictionary<string, string> parameters = new Dictionary<string, string>
{
{"grant_type", "password"},
{"client_id", Options.ClientId},
{"client_secret", Options.ClientSecret},
{"username", Options.UserName},
{"password", Options.Password},
{"scope", Options.Scopes}
};
FormUrlEncodedContent content = new FormUrlEncodedContent(parameters);
HttpResponseMessage response = await Client.PostAsync(tokenEndpoint, content);
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
using JsonDocument document = JsonDocument.Parse(json);
string token = document.RootElement.GetProperty("access_token").GetString();
return $"Bearer {token}";
}
}