Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Step Up #95

Merged
merged 10 commits into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions IdentityServer/v6/UserInteraction/StepUp/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "IdentityServerHost",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build-identityServerHost",
"program": "${workspaceFolder}/IdentityServerHost/bin/Debug/net6.0/IdentityServerHost.dll",
"args": [],
"cwd": "${workspaceFolder}/IdentityServerHost",
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
{
"name": "Client",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build-client",
"program": "${workspaceFolder}/Client/bin/Debug/net6.0/Client.dll",
"args": [],
"cwd": "${workspaceFolder}/Client",
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
{
"name": "Api",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build-api",
"program": "${workspaceFolder}/Api/bin/Debug/net6.0/Api.dll",
"args": [],
"cwd": "${workspaceFolder}/Api",
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
],
"compounds": [
{
"name": "All",
"configurations": ["Api","Client","IdentityServerHost"]
}
]
}
41 changes: 41 additions & 0 deletions IdentityServer/v6/UserInteraction/StepUp/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build-identityServerHost",
"type": "process",
"command": "dotnet",
"args": [
"build",
"${workspaceFolder}/IdentityServerHost/IdentityServerHost.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "build-client",
"type": "process",
"command": "dotnet",
"args": [
"build",
"${workspaceFolder}/Client/Client.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "build-api",
"type": "process",
"command": "dotnet",
"args": [
"build",
"${workspaceFolder}/Api/Api.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}
11 changes: 11 additions & 0 deletions IdentityServer/v6/UserInteraction/StepUp/Api/Api.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<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.4.0"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.12"/>
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

using Microsoft.AspNetCore.Authorization;

namespace Api.Authorization;

public class MaxAgeHandler : AuthorizationHandler<MaxAgeRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext ctx,
MaxAgeRequirement requirement)
{
var authTimeClaim = ctx.User.FindFirst("auth_time")?.Value;
if (authTimeClaim == null)
{
return Task.CompletedTask;
}

var authTime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(authTimeClaim));

var timeSinceAuth = DateTime.UtcNow - authTime;

if(timeSinceAuth < requirement.MaxAge)
{
ctx.Succeed(requirement);
}

return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Authorization;

namespace Api.Authorization;

public class MaxAgeRequirement : IAuthorizationRequirement
{
public MaxAgeRequirement(TimeSpan maxAge)
{
MaxAge = maxAge;
}

public TimeSpan MaxAge { get; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System.Net.Http.Headers;
using System.Text;
using Api.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.Net.Http.Headers;

public class StepUpAuthorizationMiddlewareResultHandler
: IAuthorizationMiddlewareResultHandler
{
private readonly AuthorizationMiddlewareResultHandler defaultHandler = new();

public async Task HandleAsync(
RequestDelegate next,
HttpContext context,
AuthorizationPolicy policy,
PolicyAuthorizationResult authResult)
{
// If the authorization was forbidden due to a step-up requirement, set
// the status code and WWW-Authenticate header to indicate that step-up
// is required
if (authResult.Forbidden)
{
var maxAgeReq = authResult.AuthorizationFailure!.FailedRequirements
.OfType<MaxAgeRequirement>().FirstOrDefault();
var mfaReq = authResult.AuthorizationFailure!.FailedRequirements
.OfType<ClaimsAuthorizationRequirement>()
.FirstOrDefault(r => r.ClaimType == "amr" && r.AllowedValues!.Contains("mfa"));

if (maxAgeReq != null || mfaReq != null)
{
var header = new StepUpWWWAuthenticateHeader();
if (maxAgeReq != null)
{
header.MaxAge = (int)maxAgeReq.MaxAge.TotalSeconds;
}
if (mfaReq != null)
{
header.AcrValues = "mfa";
}
context.Response.Headers.WWWAuthenticate = header.ToString();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
}
// Fall back to the default implementation.
await defaultHandler.HandleAsync(next, context, policy, authResult);
}
}


public class StepUpWWWAuthenticateHeader
{
private readonly string Error = "insufficient_user_authentication";
private string ErrorDescription {
get
{
var ret = string.Empty;
if (MaxAge != null)
{
ret += "More recent authentication is required. ";
}
if (AcrValues != null)
{
ret += "MFA is required. ";
}
return ret;
}
}
public int? MaxAge { get; set; }
public string? AcrValues { get; set; }

public override string ToString()
{
var props = new List<string> {
$"Bearer error=\"{Error}\"",
$"error_description=\"{ErrorDescription}\""
};
if(MaxAge != null)
{
props.Add($"max_age={MaxAge}");
}
if(AcrValues != null)
{
props.Add($"acr_values={AcrValues}");
}
return string.Join(',', props);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Api.Controllers;

[ApiController]
[Route("step-up")]
public class StepUp : ControllerBase
{
private readonly ILogger<StepUp> _logger;

public StepUp(ILogger<StepUp> logger)
{
_logger = logger;
}

[HttpGet]
[Route("max-age")]
[Authorize("MaxAgeOneMinute")]
public IEnumerable<string> MaxAge()
{
yield return ShowAge();
}

[HttpGet]
[Route("mfa")]
[Authorize("MfaRequired")]
public IEnumerable<string> MfaRequired()
{
yield return ShowAmrValues();
}


[HttpGet]
[Route("both")]
[Authorize("RecentMfa")]
public IEnumerable<string> Both()
{
yield return ShowAge();
yield return ShowAmrValues();
}

[HttpGet]
[Route("neither")]
[Authorize]
public IEnumerable<string> Neither()
{
yield return $"Request is authenticated";
}

private string ShowAge()
{
var authTime = long.Parse(User.FindFirst("auth_time")!.Value);
var age = DateTime.UtcNow - DateTimeOffset.FromUnixTimeSeconds(authTime);
return $"Authenticated {age.TotalSeconds} seconds ago";
}

private string ShowAmrValues()
{
var amrValues = string.Join(',', User.FindAll("amr").Select(c => c.Value));
return $"Authenticated using {amrValues}";
}
}
54 changes: 54 additions & 0 deletions IdentityServer/v6/UserInteraction/StepUp/Api/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Api.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication("jwt")
.AddJwtBearer("jwt", opt =>
{
opt.Authority = "https://localhost:5001";
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidTypes = new [] { "at+jwt" }
};
opt.MapInboundClaims = false;
});

builder.Services.AddAuthorization(opt =>
{
opt.AddPolicy("MaxAgeOneMinute", p =>
{
p.RequireAuthenticatedUser();
p.AddRequirements(new MaxAgeRequirement(TimeSpan.FromMinutes(1)));
});
opt.AddPolicy("MfaRequired", p =>
{
p.RequireAuthenticatedUser();
p.RequireClaim("amr", "mfa");
});
opt.AddPolicy("RecentMfa", p =>
{
p.RequireAuthenticatedUser();
p.RequireClaim("amr", "mfa");
p.AddRequirements(new MaxAgeRequirement(TimeSpan.FromMinutes(1)));
});
});

builder.Services.AddSingleton<IAuthorizationHandler, MaxAgeHandler>();
builder.Services.AddSingleton<IAuthorizationMiddlewareResultHandler, StepUpAuthorizationMiddlewareResultHandler>();

builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7001;",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions IdentityServer/v6/UserInteraction/StepUp/Api/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Loading