Skip to content

Commit

Permalink
Added native client app
Browse files Browse the repository at this point in the history
  • Loading branch information
juunas11 committed May 31, 2018
1 parent 8ee78f6 commit 453a2ca
Show file tree
Hide file tree
Showing 17 changed files with 325 additions and 86 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;

namespace Joonasw.AzureAdApiSample.Api.Authorization
{
public class AzureAdScopeClaimTransformation : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var scopeClaims = principal.FindAll(Constants.ScopeClaimType).ToList();
if (scopeClaims.Count != 1 || !scopeClaims[0].Value.Contains(' '))
{
// Caller has no scopes or has multiple scopes (already split)
// or they have only one scope
return Task.FromResult(principal);
}

Claim claim = scopeClaims[0];
string[] scopes = claim.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries);
IEnumerable<Claim> claims = scopes.Select(s => new Claim(Constants.ScopeClaimType, s));

return Task.FromResult(new ClaimsPrincipal(new ClaimsIdentity(principal.Identity, claims)));
}
}
}
7 changes: 7 additions & 0 deletions Joonasw.AzureAdApiSample.Api/Authorization/Constants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Joonasw.AzureAdApiSample.Api.Authorization
{
public static class Constants
{
public const string ScopeClaimType = "http://schemas.microsoft.com/identity/claims/scope";
}
}
19 changes: 0 additions & 19 deletions Joonasw.AzureAdApiSample.Api/Authorization/ScopeRequirement.cs

This file was deleted.

This file was deleted.

38 changes: 17 additions & 21 deletions Joonasw.AzureAdApiSample.Api/Controllers/TodosController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,33 @@

namespace Joonasw.AzureAdApiSample.Api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class TodosController : Controller
public class TodosController : ControllerBase
{
// In-memory data-store for testing.
private readonly List<TodoItem> _todoItems;

public TodosController()
private static readonly List<TodoItem> TodoItems = new List<TodoItem>
{
_todoItems = new List<TodoItem>
new TodoItem
{
new TodoItem
{
Id = Guid.NewGuid(),
Text = "Implement authentication",
IsDone = true
}
};
}
Id = Guid.NewGuid(),
Text = "Implement authentication",
IsDone = true
}
};

// GET api/todos
[HttpGet]
public IActionResult Get()
{
return Ok(_todoItems);
return Ok(TodoItems);
}

// GET api/todos/guid-value
[HttpGet("{id}")]
public IActionResult Get(Guid id)
{
var item = _todoItems.FirstOrDefault(i => i.Id == id);
TodoItem item = TodoItems.FirstOrDefault(i => i.Id == id);
if(item == null)
{
return NotFound();
Expand All @@ -51,7 +47,7 @@ public IActionResult Post([FromBody]TodoItem model)
{
model.Id = Guid.NewGuid();

_todoItems.Add(model);
TodoItems.Add(model);
return CreatedAtAction(nameof(Get), new{id = model.Id}, model);
}

Expand All @@ -61,14 +57,14 @@ public IActionResult Put(Guid id, [FromBody]TodoItem model)
{
model.Id = id;

var item = _todoItems.FirstOrDefault(i => i.Id == id);
TodoItem item = TodoItems.FirstOrDefault(i => i.Id == id);
if(item == null)
{
return NotFound();
}

_todoItems.Remove(item);
_todoItems.Add(model);
TodoItems.Remove(item);
TodoItems.Add(model);

return NoContent();
}
Expand All @@ -77,10 +73,10 @@ public IActionResult Put(Guid id, [FromBody]TodoItem model)
[HttpDelete("{id}")]
public void Delete(Guid id)
{
var item = _todoItems.FirstOrDefault(i => i.Id == id);
TodoItem item = TodoItems.FirstOrDefault(i => i.Id == id);
if(item != null)
{
_todoItems.Remove(item);
TodoItems.Remove(item);
}
}
}
Expand Down
10 changes: 3 additions & 7 deletions Joonasw.AzureAdApiSample.Api/Joonasw.AzureAdApiSample.Api.csproj
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.8" />
</ItemGroup>

<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.0" />
</ItemGroup>

</Project>
7 changes: 3 additions & 4 deletions Joonasw.AzureAdApiSample.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@ public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHost BuildWebHost(string[] args) =>
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
.UseStartup<Startup>();
}
}
3 changes: 1 addition & 2 deletions Joonasw.AzureAdApiSample.Api/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand All @@ -26,4 +25,4 @@
"applicationUrl": "http://localhost:2673/"
}
}
}
}
8 changes: 5 additions & 3 deletions Joonasw.AzureAdApiSample.Api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using System.Collections.Generic;
using Joonasw.AzureAdApiSample.Api.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -24,13 +26,13 @@ public void ConfigureServices(IServiceCollection services)
services.AddMvc(o =>
{
o.Filters.Add(new AuthorizeFilter("default"));
});
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

services.AddAuthorization(o =>
{
o.AddPolicy("default", policy =>
{
policy.Requirements.Add(new ScopeRequirement("user_impersonation"));
policy.RequireClaim(Constants.ScopeClaimType, "user_impersonation");
});
});

Expand All @@ -51,7 +53,7 @@ public void ConfigureServices(IServiceCollection services)
}
};
});
services.AddSingleton<IAuthorizationHandler, ScopeRequirementHandler>();
services.AddSingleton<IClaimsTransformation, AzureAdScopeClaimTransformation>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
Expand Down
13 changes: 13 additions & 0 deletions Joonasw.AzureAdApiSample.ConsoleNativeClient/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="AzureAd:Authority" value="" />
<add key="AzureAd:ClientId" value="" />
<add key="AzureAd:RedirectUri" value="" />
<add key="AzureAd:ApiResourceUri" value="" />
<add key="AzureAd:ApiBaseUrl" value="" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?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')" />
<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>
<LangVersion>7.2</LangVersion>
</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" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
23 changes: 23 additions & 0 deletions Joonasw.AzureAdApiSample.ConsoleNativeClient/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Threading.Tasks;

namespace Joonasw.AzureAdApiSample.ConsoleNativeClient
{
class Program
{
static async Task Main(string[] args)
{
var todoApiClient = new TodoApiClient();
await todoApiClient.ListTodosAsync();
Guid id = await todoApiClient.CreateTodoAsync(new TodoItem
{
Text = "Test from Console Native app",
IsDone = false
});
await todoApiClient.ListTodosAsync();
await todoApiClient.DeleteTodoAsync(id);
await todoApiClient.ListTodosAsync();
Console.ReadLine();
}
}
}
Loading

0 comments on commit 453a2ca

Please sign in to comment.