1

I'm currently migrating an ASP.Net MVC 6 app to Core Net6. In addition to the default Controller/Action/Id route, I'm creating an additional route that contains a customerkey in the URL:

app.MapControllerRoute(
     name: "ManagingCustomer",
     pattern: "{customerkey:int}/{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
     name: "Default",
     pattern: "{controller=Home}/{action=Index}/{id?}");

Within the app, a user can manage their own account or other accounts to which they have access. When they are managing an account other than their own, I would navigate with the prepended customerkey route data.

If a URL contains the customerkey route data item, where in the pipeline can I inject code to validate that the currently authenticated user actually has access to the requested account? I would like this run on every request and don't necessarily want to add code to every controller and action in order to support it. In the old MVC6 app, I would have done this in global.asax.cs. I just don't know where this fits in the core world. I'm guessing it falls into middleware? Any help would be appreciated. Thanks.

1
  • You can look into this thread. Here I have answered a similar question, you can create an action filter and register globally. In that answer I have also explained to add a custom attribute on the action that I guess is not needed in your case. stackoverflow.com/questions/74121543/… Commented Oct 26, 2022 at 5:31

1 Answer 1

0

If you already registed authoriztion policies ,i think you could try as below:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "ManageCustomer",
                    pattern: "somesection/{controller=Home}/{action=Index}/{id?}").RequireAuthorization("Policyname");
                .......
            });

And maybe you could try with Fallbackpolicy as this document:

If you just want to get the customerkey and validate it in your middleware,you could try as below:

app.Use(
            async (context, next) =>
            {
                
                var routevalue = context.Request.RouteValues;
                var customerkey = routevalue.ContainsKey("customerkey") ? routevalue["customerkey"].ToString() : "";
                //add your logical here
                if (customerkey != "")
                {
                    await next.Invoke();
                }
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                await context.Response.WriteAsync("ErrorInfo");
            });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.