ASP.NET Core 2.1 MVC, Can we set a restriction to a controller in appsetting.json? WestWind Globalization url

170 views Asked by At

I have a path in my application for handling the string resources on the site. The controller and action are managed by a 3rd party library so I can't really apply to authorize attribute there.

I am using the WestWind Globalization library which makes a URL like https://localhost:44328/LocalizationAdmin/index.html.

Can I restring any controller in my appsetting.json as we do in the web.config in old ASP.NET MVC?

Something similar to below in ASP.NET Core?

<location path="LocalizationAdmin">
  <system.web>
    <authorization>
      <deny users="*">
    </authorization>
  </system.web>
</location>
1

There are 1 answers

2
itminus On BEST ANSWER

Web.config is used by IIS. But ASP.NET Core could be deployed without IIS. When cooperating with Nginx, there's no such way to configure authorization in appsettings.json.

A much more simple approach is to setup a simple middleware:

app.Use(async(ctx , next)=>{
    // passby all other requests
    if(!ctx.Request.Path.StartsWithSegments("/LocalizationAdmin")){
        await next();      
    }
    else {
        var user = ctx.User;               // now we have the current user
        var resource = new { /* ... */ };  // construct description as you like
        var authZService = ctx.RequestServices.GetRequiredService<IAuthorizationService>();
        var accessible =await  authZService.AuthorizeAsync(user, resource,"MyPolicyName");
        if(accessible.Succeeded){
            await next();          
        }else{
            ctx.Response.StatusCode = 403;
            await ctx.Response.WriteAsync("not allowed");
        }
    }
});