Skip to content

Commit 56cbd81

Browse files
Add a snippet that shows wo to use AuthorizationMiddlewareResultHandler (#20193)
* Add a snippet that shows wo to use AuthorizationMiddlewareResultHandler * Bring over pravan AuthMiddlewareResultHander (#20198) * Bring over pravan AuthMiddlewareResultHander * clean up * react to feedback * react to feedback * react to feedback * react to feedback * Apply suggestions from code review Co-authored-by: Pranav K <prkrishn@hotmail.com> * react to feedback * react to feedback * react to feedback Co-authored-by: Pranav K <prkrishn@hotmail.com> Co-authored-by: Rick Anderson <3605364+Rick-Anderson@users.noreply.github.com>
1 parent b89e130 commit 56cbd81

4 files changed

Lines changed: 127 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
title: Customize the behavior of AuthorizationMiddleware
3+
author: pranavkm
4+
ms.author: prkrishn
5+
description: This article explains how to customize the result handling of AuthorizationMiddleware.
6+
monikerRange: '>= aspnetcore-5.0'
7+
uid: security/authorization/authorizationmiddlewareresulthandler
8+
---
9+
# Customize the behavior of AuthorizationMiddleware
10+
11+
Applications can register a `Microsoft.AspNetCore.Authorization.IAuthorizationMiddlewareResultHandler` to customize the way the middleware handles the authorization results. Applications can use the customized middleware to:
12+
13+
* Return customized responses.
14+
* Enhance the default challenge or forbid responses.
15+
16+
The following code shows an example of an authorization handler that returns a custom response for certain kinds of authorization failures:
17+
18+
[!code-csharp[](customizingauthorizationmiddlewareresponse/sample/AuthorizationMiddlewareResultHandlerSample/MyAuthorizationMiddlewareResultHandler.cs)]
19+
20+
Register `MyAuthorizationMiddlewareResultHandler` in `Startup.ConfigureServices`:
21+
22+
[!code-csharp[](customizingauthorizationmiddlewareresponse/sample/AuthorizationMiddlewareResultHandlerSample/Startup.cs?name=snippet)]
23+
24+
<!-- <xref:Microsoft.AspNetCore.Authorization.IAuthorizationMiddlewareResultHandler /> -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Authorization.Policy;
3+
using Microsoft.AspNetCore.Http;
4+
using System.Linq;
5+
using System.Net;
6+
using System.Threading.Tasks;
7+
8+
public class MyAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
9+
{
10+
private readonly AuthorizationMiddlewareResultHandler
11+
DefaultHandler = new AuthorizationMiddlewareResultHandler();
12+
13+
public async Task HandleAsync(
14+
RequestDelegate requestDelegate,
15+
HttpContext httpContext,
16+
AuthorizationPolicy authorizationPolicy,
17+
PolicyAuthorizationResult policyAuthorizationResult)
18+
{
19+
// if the authorization was forbidden and the resource had specific requirements,
20+
// provide a custom response.
21+
if (Show404ForForbiddenResult(policyAuthorizationResult))
22+
{
23+
// Return a 404 to make it appear as if the resource does not exist.
24+
httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
25+
return;
26+
}
27+
28+
// Fallback to the default implementation.
29+
await DefaultHandler.HandleAsync(requestDelegate, httpContext, authorizationPolicy,
30+
policyAuthorizationResult);
31+
}
32+
33+
bool Show404ForForbiddenResult(PolicyAuthorizationResult policyAuthorizationResult)
34+
{
35+
return policyAuthorizationResult.Forbidden &&
36+
policyAuthorizationResult.AuthorizationFailure.FailedRequirements.OfType<
37+
Show404Requirement>().Any();
38+
}
39+
}
40+
41+
public class Show404Requirement : IAuthorizationRequirement { }
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Builder;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.AspNetCore.HttpsPolicy;
5+
using Microsoft.Extensions.Configuration;
6+
using Microsoft.Extensions.DependencyInjection;
7+
using Microsoft.Extensions.Hosting;
8+
using System;
9+
using System.Collections.Generic;
10+
using System.Linq;
11+
using System.Threading.Tasks;
12+
13+
namespace AuthorizationMiddlewareResultHandlerSample
14+
{
15+
public class Startup
16+
{
17+
public Startup(IConfiguration configuration)
18+
{
19+
Configuration = configuration;
20+
}
21+
22+
public IConfiguration Configuration { get; }
23+
24+
#region snippet
25+
public void ConfigureServices(IServiceCollection services)
26+
{
27+
services.AddRazorPages();
28+
services.AddSingleton<IAuthorizationMiddlewareResultHandler,
29+
MyAuthorizationMiddlewareResultHandler>();
30+
}
31+
#endregion
32+
33+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
34+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
35+
{
36+
if (env.IsDevelopment())
37+
{
38+
app.UseDeveloperExceptionPage();
39+
}
40+
else
41+
{
42+
app.UseExceptionHandler("/Error");
43+
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
44+
app.UseHsts();
45+
}
46+
47+
app.UseHttpsRedirection();
48+
app.UseStaticFiles();
49+
50+
app.UseRouting();
51+
52+
app.UseAuthorization();
53+
54+
app.UseEndpoints(endpoints =>
55+
{
56+
endpoints.MapRazorPages();
57+
});
58+
}
59+
}
60+
}

aspnetcore/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1121,6 +1121,8 @@
11211121
uid: security/authorization/policies
11221122
- name: Authorization policy providers
11231123
uid: security/authorization/iauthorizationpolicyprovider
1124+
- name: Customize the behavior of AuthorizationMiddleware
1125+
uid: security/authorization/authorizationmiddlewareresulthandler
11241126
- name: Dependency injection in requirement handlers
11251127
uid: security/authorization/dependencyinjection
11261128
- name: Resource-based authorization

0 commit comments

Comments
 (0)