Exploring Neon as a Serverless Postgres Alternative for .NET Applications on Azure - Part 1 (Simple ASP.NET Core on App Service)10 lut 2025
Blog | programowanie | .net | c# | azure | IT
I was prompted to write this post by this question. In general, the question is about using ASP.NET Core built-in authorization to restrict access to a middleware. In ASP.NET Core the authorization mechanism is well exposed for MVC (through AuthorizeAttribute), but for middleware it's a manual job (at least for now). The reason for that might be the fact that there is no too many terminal middleware.
This was not the first time I've received this question, so I've quickly responded with typical code to achieve the task. But, after some thinking, I've decided I will put a detailed answer here.
At its core, the authorization in ASP.NET Core is based on policies. Other available ways of specifying requirements (roles, claims) are in the end evaluated to policies. This means that it is enough to be able to validate a policy for the current user. This can be easily done with help of IAuthorizationService. All one needs is a policy name and HttpContext. Following authorization middleware gets the job done.
public class AuthorizationMiddleware
{
private readonly RequestDelegate _next;
private readonly string _policyName;
public AuthorizationMiddleware(RequestDelegate next, string policyName)
{
_next = next;
_policyName = policyName;
}
public async Task Invoke(HttpContext httpContext, IAuthorizationService authorizationService)
{
AuthorizationResult authorizationResult =
await authorizationService.AuthorizeAsync(httpContext.User, null, _policyName);
if (!authorizationResult.Succeeded)
{
await httpContext.ChallengeAsync();
return;
}
await _next(httpContext);noreply@blogger.com (Tomasz Pęczek)