Skip to content
This repository was archived by the owner on Feb 16, 2023. It is now read-only.

Authorization

Fernando Escolar edited this page May 6, 2021 · 1 revision

RoutingRoutes is fully integrated with the Asp.Net authorization framework. You can add a global policy with an authorization requirement for all endpoints:

public void ConfigureServices(IServiceCollection services)
{
  services.AddRouteRecords();

  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .Add...(options => { ... });

  services.AddAuthorization(options =>
  {
      options.FallbackPolicy = new AuthorizationPolicyBuilder()
                                     .RequireAuthenticatedUser()
                                     .Build();
  });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  app.UseRouting();
  app.UseAuthorization();
  app.UseEndpoints(endpoints => endpoints.MapRouteRecords());
}

In the same way you get a IEndpointConventionBuilder when you register an endpoint, when you map objects of type RouteRecord, you get an object of type:

  • IRecordEndpointConventionBuilder for one record map call (MapRouteRecord).
  • IRecordEndpointConventionBuilderCollection for multiple records map call (MapRouteRecords).
interface IRecordEndpointConventionBuilder
  : IEndpointConventionBuilder
{
  Type RouteRecordType { get; }
}

interface IRecordEndpointConventionBuilderCollection
  : IEndpointConventionBuilder, IEnumerable<IRecordEndpointConventionBuilder>
{
}

So you can use the convention builders for each RouteRecord:

public void ConfigureServices(IServiceCollection services)
{
  services.AddRouteRecords();

  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .Add...(options => { ... });

  services.AddAuthorization();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  app.UseRouting();
  app.UseAuthorization();
  app.UseEndpoints(endpoints
        => endpoints.MapRouteRecords()
                    .Where(x => x.RouteRecordType.IsNot<Hello>())
                    .ToList()
                    .ForEach(y => y.RequireAuthorization()));
}

Clone this wiki locally