Skip to content
Snippets Groups Projects
Commit 2bc087d3 authored by Klaus Fischer's avatar Klaus Fischer
Browse files

Moved OAuth to services

parent 93b5a081
No related branches found
No related tags found
1 merge request!3Feature/440 mvp net sdk part 1
...@@ -8,15 +8,16 @@ ...@@ -8,15 +8,16 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.7.0"/> <PackageReference Include="FluentAssertions" Version="6.7.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="NUnit" Version="3.13.2"/> <PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0"/> <PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="coverlet.collector" Version="3.1.0"/> <PackageReference Include="coverlet.collector" Version="3.1.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FitConnect\FitConnect.csproj"/> <ProjectReference Include="..\FitConnect\FitConnect.csproj" />
<ProjectReference Include="..\Services\Services.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
using System;
using System.IO;
using FitConnect;
using FitConnect.Services;
using FluentAssertions;
using Newtonsoft.Json;
using NUnit.Framework;
namespace E2ETests;
public class OAuthServiceTest {
private OAuthService _oAuthService = null!;
private string _clientId;
private string _clientSecret;
[OneTimeSetUp]
public void OneTimeSetup() {
// relative to the project execution directory
const string secretFile = "../../../http-client.private.env.json";
if (!File.Exists(secretFile)) {
// If the secret file is not found, create it with the default values
// The file will be pretty in C#11, when """ is introduced
File.WriteAllText(secretFile, @"
{
""sender"": {
""id"": ""00000000-0000-0000-0000-000000000000"",
""secret"": ""0000000000000000000000000000000000000000000"",
""scope"": ""send:region:DE""
}
}");
throw new Exception("Please fill the secret.json file with your sender credentials");
}
var jsonContent = File.ReadAllText(secretFile);
var secret = JsonConvert.DeserializeObject<dynamic>(jsonContent);
_clientId = secret.sender.id;
_clientSecret = secret.sender.secret;
}
[SetUp]
public void SetUp() {
var endpoints = FitConnectEndpoints.Create(FitConnectEndpoints.EndpointType.Development);
_oAuthService = new OAuthService(endpoints.TokenUrl);
}
[Test]
public void GetAccessToken_ExpiresInShouldBe1800_WithoutScope() {
var token = _oAuthService.GetTokenAsync(_clientId, _clientSecret).Result;
token.Should().NotBeNull();
token!.ExpiresIn.Should().Be(1800);
token.Scope.Should().Be("send:region:DE");
}
[Test]
public void GetAccessToken_ScopeShouldMatch_WithScope() {
var token = _oAuthService.GetTokenAsync(_clientId, _clientSecret, "send:region:DE01010")
.Result;
token.Should().NotBeNull();
token!.ExpiresIn.Should().Be(1800);
token.Scope.Should().Be("send:region:DE01010");
}
}
...@@ -53,19 +53,4 @@ public class SenderTest { ...@@ -53,19 +53,4 @@ public class SenderTest {
_clientSecret.Should().NotBe("0000000000000000000000000000000000000000000"); _clientSecret.Should().NotBe("0000000000000000000000000000000000000000000");
} }
[Test]
public void GetAccessToken_ExpiresInShouldBe1800_WithoutScope() {
var token = _sender.GetTokenAsync(_clientId, _clientSecret).Result;
token.Should().NotBeNull();
token!.ExpiresIn.Should().Be(1800);
token.Scope.Should().Be("send:region:DE");
}
[Test]
public void GetAccessToken_ScopeShouldMatch_WithScope() {
var token = _sender.GetTokenAsync(_clientId, _clientSecret, "send:region:DE01010").Result;
token.Should().NotBeNull();
token!.ExpiresIn.Should().Be(1800);
token.Scope.Should().Be("send:region:DE01010");
}
} }
...@@ -7,7 +7,7 @@ using Microsoft.Extensions.Logging; ...@@ -7,7 +7,7 @@ using Microsoft.Extensions.Logging;
namespace FitConnect.BaseClasses; namespace FitConnect.BaseClasses;
public abstract class FunctionalBaseClass: RestCallService { public abstract class FunctionalBaseClass {
protected readonly ILogger? Logger; protected readonly ILogger? Logger;
public readonly IEncryption Encryption; public readonly IEncryption Encryption;
...@@ -32,42 +32,6 @@ public abstract class FunctionalBaseClass: RestCallService { ...@@ -32,42 +32,6 @@ public abstract class FunctionalBaseClass: RestCallService {
public FitConnectEndpoints Endpoints { get; } public FitConnectEndpoints Endpoints { get; }
/// <summary>
/// Requesting an OAuth token from the FitConnect API.
/// <para>You can get the Client ID and Client Secret from the FitConnect Self Service portal
/// under <br/>
/// https://portal.auth-testing.fit-connect.fitko.dev</para>
/// </summary>
/// <param name="clientId">Your client Id</param>
/// <param name="clientSecret">Your client Secret</param>
/// <param name="scope">Scope if needed</param>
/// <returns>The received token or null</returns>
public async Task<OAuthAccessToken?> GetTokenAsync(string clientId, string clientSecret,
string? scope = null) {
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
MediaTypeWithQualityHeaderValue.Parse("application/json"));
var requestContent = new Dictionary<string, string> {
{ "grant_type", "client_credentials" },
{ "client_id", clientId },
{ "client_secret", clientSecret }
};
if (scope != null)
requestContent["scope"] = scope;
var content = new FormUrlEncodedContent(requestContent);
var request = new HttpRequestMessage(HttpMethod.Post, Endpoints.TokenUrl) {
Content = content,
Method = HttpMethod.Post
};
var response = await client.SendAsync(request);
return await response.Content.ReadFromJsonAsync<OAuthAccessToken>();
}
/// <summary> /// <summary>
/// Receive the SET data /// Receive the SET data
......
...@@ -24,7 +24,6 @@ ...@@ -24,7 +24,6 @@
<ItemGroup> <ItemGroup>
<Folder Include="Interfaces" /> <Folder Include="Interfaces" />
<Folder Include="Models\Api" />
</ItemGroup> </ItemGroup>
</Project> </Project>
...@@ -8,7 +8,7 @@ namespace FitConnect; ...@@ -8,7 +8,7 @@ namespace FitConnect;
/// <summary> /// <summary>
/// Client to the FitConnect Routing Api /// Client to the FitConnect Routing Api
/// </summary> /// </summary>
public class Routing : RestCallService { public class Routing {
private readonly ILogger? _logger; private readonly ILogger? _logger;
private readonly FitConnectEndpoints _endpoints; private readonly FitConnectEndpoints _endpoints;
private readonly X509Certificate2? _certificate; private readonly X509Certificate2? _certificate;
......
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace FitConnect.Models; namespace FitConnect.Services.Models;
public class OAuthAccessToken { public class OAuthAccessToken {
[JsonPropertyName("access_token")] [JsonPropertyName("access_token")]
......
using System.Net.Http.Headers;
using System.Net.Http.Json;
using FitConnect.Services.Models;
namespace FitConnect.Services;
public class OAuthService {
private readonly string _tokenUrl;
public OAuthService(string tokenUrl) {
_tokenUrl = tokenUrl;
}
/// <summary>
/// Requesting an OAuth token from the FitConnect API.
/// <para>You can get the Client ID and Client Secret from the FitConnect Self Service portal
/// under <br/>
/// https://portal.auth-testing.fit-connect.fitko.dev</para>
/// </summary>
/// <param name="clientId">Your client Id</param>
/// <param name="clientSecret">Your client Secret</param>
/// <param name="scope">Scope if needed</param>
/// <returns>The received token or null</returns>
public async Task<OAuthAccessToken?> GetTokenAsync(string clientId, string clientSecret,
string? scope = null) {
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
MediaTypeWithQualityHeaderValue.Parse("application/json"));
var requestContent = new Dictionary<string, string> {
{ "grant_type", "client_credentials" },
{ "client_id", clientId },
{ "client_secret", clientSecret }
};
if (scope != null)
requestContent["scope"] = scope;
var content = new FormUrlEncodedContent(requestContent);
var request = new HttpRequestMessage(HttpMethod.Post, _tokenUrl) {
Content = content,
Method = HttpMethod.Post
};
var response = await client.SendAsync(request);
return await response.Content.ReadFromJsonAsync<OAuthAccessToken>();
}
}
using System.Net.Http.Json; using System.Net.Http.Json;
using System.Text; using System.Text;
namespace FitConnect.BaseClasses; namespace FitConnect.Services;
public abstract class RestCallService { public abstract class RestCallService {
private async Task<T?> RestCall<T>(Uri uri, HttpMethod method, string body) { private async Task<T?> RestCall<T>(Uri uri, HttpMethod method, string body) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment