Skip to content

Commit

Permalink
Work-in-progress, adding background job, refactoring apps to Core and…
Browse files Browse the repository at this point in the history
… using the ConfigurationBuilder APIs
  • Loading branch information
juunas11 committed May 31, 2018
1 parent 453a2ca commit a78d98d
Show file tree
Hide file tree
Showing 15 changed files with 142 additions and 131 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<UserSecretsId>bee0443a-9bf6-45ea-8e8b-f49272936717</UserSecretsId>
</PropertyGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions Joonasw.AzureAdApiSample.Api/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
}
},
"Authentication": {
"Authority": "https://login.microsoftonline.com/joonasapps.onmicrosoft.com/",
"AppIdUri": "https://joonasapps.onmicrosoft.com/fa87d15c-fbc9-4fe5-95f5-0b36108eb305",
"ClientId": "6657d9d4-a9c1-4fb1-81b0-8a8d42b6a9cf"
"Authority": "https://login.microsoftonline.com/yourtenant.onmicrosoft.com/",
"AppIdUri": "https://yourtenant.onmicrosoft.com/guid-here",
"ClientId": "client-id-also-known-as-application-id"
}
}
11 changes: 11 additions & 0 deletions Joonasw.AzureAdApiSample.ConsoleBackgroundJob/JobSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Joonasw.AzureAdApiSample.ConsoleBackgroundJob
{
public class JobSettings
{
public string Authority { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string ApiResourceUri { get; set; }
public string ApiBaseUrl { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<LangVersion>7.2</LangVersion>
<UserSecretsId>bee0443a-9bf6-45ea-8e8b-f49272936718</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="3.19.6" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
22 changes: 22 additions & 0 deletions Joonasw.AzureAdApiSample.ConsoleBackgroundJob/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace Joonasw.AzureAdApiSample.ConsoleBackgroundJob
{
class Program
{
static async Task Main(string[] args)
{
IConfiguration config = CreateConfig();
JobSettings settings = config.Get<JobSettings>();
}

private static IConfiguration CreateConfig() =>
new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddUserSecrets<Program>()
.Build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"Authority": "",
"ClientId": "",
"ClientSecret": "",
"ApiResourceUri": "",
"ApiBaseUrl": "http://localhost:2672"
}
13 changes: 0 additions & 13 deletions Joonasw.AzureAdApiSample.ConsoleNativeClient/App.config

This file was deleted.

11 changes: 11 additions & 0 deletions Joonasw.AzureAdApiSample.ConsoleNativeClient/ClientSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Joonasw.AzureAdApiSample.ConsoleNativeClient
{
public class ClientSettings
{
public string Authority { get; set; }
public string ClientId { get; set; }
public string RedirectUri { get; set; }
public string ApiResourceUri { get; set; }
public string ApiBaseUrl { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,66 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D3973CD4-097F-4332-8D10-39B3A1F83F47}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Joonasw.AzureAdApiSample.ConsoleNativeClient</RootNamespace>
<AssemblyName>Joonasw.AzureAdApiSample.ConsoleNativeClient</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TargetFramework>netcoreapp2.1</TargetFramework>
<LangVersion>7.2</LangVersion>
<UserSecretsId>bee0443a-9bf6-45ea-8e8b-f49272936719</UserSecretsId>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory, Version=3.19.6.14301, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.3.19.6\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory.Platform, Version=3.19.6.14301, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.3.19.6\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>

<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TodoApiClient.cs" />
<Compile Include="TodoItem.cs" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="3.19.6" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>

<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

</Project>
11 changes: 10 additions & 1 deletion Joonasw.AzureAdApiSample.ConsoleNativeClient/Program.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace Joonasw.AzureAdApiSample.ConsoleNativeClient
{
class Program
{
static async Task Main(string[] args)
{
var todoApiClient = new TodoApiClient();
var config = CreateConfig();
var settings = config.Get<ClientSettings>();
var todoApiClient = new TodoApiClient(settings);
await todoApiClient.ListTodosAsync();
Guid id = await todoApiClient.CreateTodoAsync(new TodoItem
{
Expand All @@ -19,5 +22,11 @@ static async Task Main(string[] args)
await todoApiClient.ListTodosAsync();
Console.ReadLine();
}

private static IConfiguration CreateConfig() =>
new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddUserSecrets<Program>()
.Build();
}
}

This file was deleted.

37 changes: 22 additions & 15 deletions Joonasw.AzureAdApiSample.ConsoleNativeClient/TodoApiClient.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
Expand All @@ -12,16 +11,17 @@ namespace Joonasw.AzureAdApiSample.ConsoleNativeClient
{
public class TodoApiClient
{
private static readonly string Authority = ConfigurationManager.AppSettings["AzureAd:Authority"];
private static readonly string ApiResourceUri = ConfigurationManager.AppSettings["AzureAd:ApiResourceUri"];
private static readonly string ClientId = ConfigurationManager.AppSettings["AzureAd:ClientId"];
private static readonly Uri RedirectUri = new Uri(ConfigurationManager.AppSettings["AzureAd:RedirectUri"]);
private static readonly string ApiBaseUrl = ConfigurationManager.AppSettings["AzureAd:ApiBaseUrl"];
private static readonly HttpClient Client = new HttpClient();
private readonly ClientSettings _settings;

public TodoApiClient(ClientSettings settings)
{
_settings = settings;
}

public async Task ListTodosAsync()
{
using (var req = new HttpRequestMessage(HttpMethod.Get, $"{ApiBaseUrl}/api/todos"))
using (var req = new HttpRequestMessage(HttpMethod.Get, $"{_settings.ApiBaseUrl}/api/todos"))
{
string accessToken = await GetAccessTokenAsync();
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
Expand All @@ -48,7 +48,7 @@ private void ListTodosOnConsole(List<TodoItem> todos)
public async Task<Guid> CreateTodoAsync(TodoItem todoItem)
{
Console.WriteLine("---Create todo item---");
using (var req = new HttpRequestMessage(HttpMethod.Post, $"{ApiBaseUrl}/api/todos"))
using (var req = new HttpRequestMessage(HttpMethod.Post, $"{_settings.ApiBaseUrl}/api/todos"))
{
string accessToken = await GetAccessTokenAsync();
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
Expand All @@ -71,7 +71,7 @@ public async Task<Guid> CreateTodoAsync(TodoItem todoItem)
public async Task DeleteTodoAsync(Guid id)
{
Console.WriteLine("---Delete todo item---");
using (var req = new HttpRequestMessage(HttpMethod.Delete, $"{ApiBaseUrl}/api/todos/{id}"))
using (var req = new HttpRequestMessage(HttpMethod.Delete, $"{_settings.ApiBaseUrl}/api/todos/{id}"))
{
string accessToken = await GetAccessTokenAsync();
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
Expand All @@ -86,13 +86,20 @@ public async Task DeleteTodoAsync(Guid id)

private async Task<string> GetAccessTokenAsync()
{
var context = new AuthenticationContext(Authority);
var context = new AuthenticationContext(_settings.Authority);

AuthenticationResult result;
try
{
result = await context.AcquireTokenSilentAsync(_settings.ApiResourceUri, _settings.ClientId);
}
catch (AdalSilentTokenAcquisitionException)
{
DeviceCodeResult deviceCodeResult = await context.AcquireDeviceCodeAsync(_settings.ApiResourceUri, _settings.ClientId);
Console.WriteLine(deviceCodeResult.Message);
result = await context.AcquireTokenByDeviceCodeAsync(deviceCodeResult);
}

var result = await context.AcquireTokenAsync(
ApiResourceUri,
ClientId,
RedirectUri,
new PlatformParameters(PromptBehavior.Auto));
return result.AccessToken;
}
}
Expand Down
7 changes: 7 additions & 0 deletions Joonasw.AzureAdApiSample.ConsoleNativeClient/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"Authority": "https://login.microsoftonline.com/yourtenant.onmicrosoft.com",
"ClientId": "application-id-here",
"ApiResourceUri": "https://yourtenant.onmicrosoft.com/some-guid",
"RedirectUri": "https://yourtenant.onmicrosoft.com/TodoClient",
"ApiBaseUrl": "http://localhost:2672"
}
5 changes: 0 additions & 5 deletions Joonasw.AzureAdApiSample.ConsoleNativeClient/packages.config

This file was deleted.

6 changes: 6 additions & 0 deletions Joonasw.AzureAdApiSample.sln
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Joonasw.AzureAdApiSample.Ap
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Joonasw.AzureAdApiSample.ConsoleNativeClient", "Joonasw.AzureAdApiSample.ConsoleNativeClient\Joonasw.AzureAdApiSample.ConsoleNativeClient.csproj", "{D3973CD4-097F-4332-8D10-39B3A1F83F47}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Joonasw.AzureAdApiSample.ConsoleBackgroundJob", "Joonasw.AzureAdApiSample.ConsoleBackgroundJob\Joonasw.AzureAdApiSample.ConsoleBackgroundJob.csproj", "{309E6F8E-F357-4AF6-ACCB-2EF9BCBE0A9F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -21,6 +23,10 @@ Global
{D3973CD4-097F-4332-8D10-39B3A1F83F47}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D3973CD4-097F-4332-8D10-39B3A1F83F47}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D3973CD4-097F-4332-8D10-39B3A1F83F47}.Release|Any CPU.Build.0 = Release|Any CPU
{309E6F8E-F357-4AF6-ACCB-2EF9BCBE0A9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{309E6F8E-F357-4AF6-ACCB-2EF9BCBE0A9F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{309E6F8E-F357-4AF6-ACCB-2EF9BCBE0A9F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{309E6F8E-F357-4AF6-ACCB-2EF9BCBE0A9F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down

0 comments on commit a78d98d

Please sign in to comment.