Skip to content

Commit

Permalink
Merge pull request #10 from TBCBank/feature/AddAuthorizationHeader
Browse files Browse the repository at this point in the history
Add Authorization Header
  • Loading branch information
lachinchaladze authored Jul 12, 2022
2 parents baa6a91 + e45db07 commit 28a80db
Show file tree
Hide file tree
Showing 12 changed files with 201 additions and 2 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public ExampleClient(HttpHelper<ExampleClient> http)
}
```
* Create class "ExampleClientOptions" and inherit from "TBC.OpenAPI.SDK.Core.OptionsBase"
* If you need client secret in options, inherit from "TBC.OpenAPI.SDK.Core.BasicAuthOptions"

```c#
public class ExampleClientOptions : OptionsBase{}
```
Expand Down Expand Up @@ -112,6 +114,22 @@ appsettings.json
}
}
```
* In case you need client secret

Program.cs
```c#
builder.Services.AddExampleClient(builder.Configuration.GetSection("ExampleClient").Get<BasicAuthOptions>());
```
appsettings.json
```json
{
"ExampleClient": {
"BaseUrl": "https://run.mocky.io/v3/7690b5f0-cc43-4c03-b07f-2240b4448931/",
"ApiKey": "abc",
"ClientSecret": "abc"
}
}
```

#### Create variable "_exampleClient" of type "IExampleClient" in controller and initialize it using dependency injection
```c#
Expand Down
7 changes: 7 additions & 0 deletions TBC.OpenAPI.SDK.Core.sln
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TBC.OpenAPI.SDK.Core.Tests"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TBC.OpenAPI.SDK.ExampleClient", "examples\TBC.OpenAPI.SDK.ExampleClient\TBC.OpenAPI.SDK.ExampleClient.csproj", "{4781CB51-82B2-4C81-8DD3-F0B8D43D4B01}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UsageExample4", "examples\UsageExample4\UsageExample4.csproj", "{4B6B8E61-2E02-4D1D-8F3A-8B7DA63F5C3B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -66,6 +68,10 @@ Global
{4781CB51-82B2-4C81-8DD3-F0B8D43D4B01}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4781CB51-82B2-4C81-8DD3-F0B8D43D4B01}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4781CB51-82B2-4C81-8DD3-F0B8D43D4B01}.Release|Any CPU.Build.0 = Release|Any CPU
{4B6B8E61-2E02-4D1D-8F3A-8B7DA63F5C3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B6B8E61-2E02-4D1D-8F3A-8B7DA63F5C3B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B6B8E61-2E02-4D1D-8F3A-8B7DA63F5C3B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B6B8E61-2E02-4D1D-8F3A-8B7DA63F5C3B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -78,6 +84,7 @@ Global
{E3DAC414-1447-4297-B9B5-EA8E14DF4DD5} = {D93C5C4E-65C3-4AE2-98B7-51BBDA578C3A}
{FD836F18-B715-4EF2-B41B-BECB4F0B6913} = {F068D92C-EC84-452F-BF81-BD548EAE5BAF}
{4781CB51-82B2-4C81-8DD3-F0B8D43D4B01} = {322E62F9-79CE-40D6-A7D2-AC2375CF4C18}
{4B6B8E61-2E02-4D1D-8F3A-8B7DA63F5C3B} = {322E62F9-79CE-40D6-A7D2-AC2375CF4C18}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6EA70694-3D75-4295-9BE5-B779CA933036}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
using TBC.OpenAPI.SDK.Core;

namespace TBC.OpenAPI.SDK.ExampleClient
{
public class ExampleClientBasicAuthOptions : BasicAuthOptions
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,19 @@ public static IServiceCollection AddExampleClient(this IServiceCollection servic
services.AddOpenApiClient<IExampleClient, ExampleClient, ExampleClientOptions>(options, configureClient, configureHttpMessageHandler);
return services;
}




public static IServiceCollection AddExampleClient(this IServiceCollection services, ExampleClientBasicAuthOptions options)
=> AddExampleClient(services, options, null, null);

public static IServiceCollection AddExampleClient(this IServiceCollection services, ExampleClientBasicAuthOptions options,
Action<HttpClient>? configureClient = null,
Func<HttpClientHandler>? configureHttpMessageHandler = null)
{
services.AddOpenApiClient<IExampleClient, ExampleClient, ExampleClientBasicAuthOptions>(options, configureClient, configureHttpMessageHandler);
return services;
}
}
}
25 changes: 25 additions & 0 deletions examples/UsageExample4/Controllers/TestController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Microsoft.AspNetCore.Mvc;
using TBC.OpenAPI.SDK.ExampleClient;
using TBC.OpenAPI.SDK.ExampleClient.Models;

namespace UsageExample4.Controllers
{
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
private readonly IExampleClient _exampleClient;

public TestController(IExampleClient exampleClient)
{
_exampleClient = exampleClient;
}

[HttpGet]
public async Task<ActionResult<SomeObject>> GetSomeObject(CancellationToken cancellationToken = default)
{
var result = await _exampleClient.GetSomeObjectAsync(cancellationToken);
return Ok(result);
}
}
}
31 changes: 31 additions & 0 deletions examples/UsageExample4/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using TBC.OpenAPI.SDK.ExampleClient;
using TBC.OpenAPI.SDK.ExampleClient.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddExampleClient(builder.Configuration.GetSection("ExampleClient").Get<ExampleClientBasicAuthOptions>());


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
31 changes: 31 additions & 0 deletions examples/UsageExample4/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:30641",
"sslPort": 44345
}
},
"profiles": {
"UsageExample4": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7137;http://localhost:5137",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
17 changes: 17 additions & 0 deletions examples/UsageExample4/UsageExample4.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\TBC.OpenAPI.SDK.ExampleClient\TBC.OpenAPI.SDK.ExampleClient.csproj" />
</ItemGroup>

</Project>
8 changes: 8 additions & 0 deletions examples/UsageExample4/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
15 changes: 15 additions & 0 deletions examples/UsageExample4/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",

"ExampleClient": {
"BaseUrl": "https://run.mocky.io/v3/7690b5f0-cc43-4c03-b07f-2240b4448931/",
"ApiKey": "abc",
"ClientSecret": "abc"
}
}
11 changes: 11 additions & 0 deletions src/TBC.OpenAPI.SDK.Core/BasicAuthOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace TBC.OpenAPI.SDK.Core
{
public abstract class BasicAuthOptions : OptionsBase
{
public string ClientSecret { get; set; } = null!;
}
}
15 changes: 13 additions & 2 deletions src/TBC.OpenAPI.SDK.Core/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Text;

namespace TBC.OpenAPI.SDK.Core.Extensions
{
Expand All @@ -15,11 +16,21 @@ public static IServiceCollection AddOpenApiClient<TClientInterface, TClientImple
{
var httpClientBuilder = services.AddHttpClient(typeof(TClientImplementation).FullName, client =>
{
client.BaseAddress = new Uri(options.BaseUrl);
if (!string.IsNullOrWhiteSpace(options.ApiKey))

if (typeof(BasicAuthOptions).IsAssignableFrom(typeof(TOptions)))
{

var opt = options as BasicAuthOptions;

string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1")
.GetBytes(opt.ApiKey + ":" + opt.ClientSecret));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
}
else if (typeof(OptionsBase).IsAssignableFrom(typeof(TOptions)))
{
client.DefaultRequestHeaders.Add("apikey", options.ApiKey);
}
client.BaseAddress = new Uri(options.BaseUrl);
configureClient?.Invoke(client);
});

Expand Down

0 comments on commit 28a80db

Please sign in to comment.