C
C#4mo ago
nox7

✅ ASP Core Attribute Logic Help

I need assistance with structuring my controller attribute logic (they're authorization attributes) in ASP Core 2 - I am using .NET 8. I have the following objects (for this purpose): ClientAccount, Dashboard, and StripeAccount. When a client accesses a route, I need to - Verify they are logged in - Verify they are accessing a Dashboard that exists - Verify they are accessing a Dashboard they have authorization to view - Verify, for some routes, the Dashboard has a connected StripeAccount My idea was to add these attributes to the controllers
[RequireClientAccount]
[RequireDashboard]
[RequireClientHasAccessToDashboard]
[RequireClientAccount]
[RequireDashboard]
[RequireClientHasAccessToDashboard]
Because some routes don't need the 3rd one. How can I approach this without each route having to run duplicate database calls? As in, RequireDashboard and RequireClientHasAccessToDashboard would both need to re-fetch the current Dashboard from the HttpContext since routes don't have any set order they run in - so they can't rely on one already having fetched the Dashboard object? Would a scoped object with static properties work to store if an object has already been fetched? Because attributes have no defined order, I am duplicating Db queries in each attribute to perform the same operation at the moment.
4 Replies
z0mb
z0mb4mo ago
Couldn't you just have one attribute, and pass in some parameters to configure what exactly you need for that specific endpoint? Then you can logically determine if they should be able to access the endpoint based off of your requirements and the provided parameters? That would avoid multiple unnecessary DB calls.
z0mb
z0mb4mo ago
Verify they are logged in : I would just use the built in [Authorize] vs [AllowAnonymous] Verify they are accessing a dashboard that exists: Verify they are accessing a dashboard they have authorization to view: Verify for some routes the Dashboard has a connected StripeAccount: https://paste.mod.gg/xtgdonyhekrc/0
BlazeBin - xtgdonyhekrc
A tool for sharing your source code with the world!
z0mb
z0mb4mo ago
That is just some boilerplate stuff to get you going, but I believe this approach would accomplish what you need. Add, subtract, or modify parameters as you see fit. Then your usage would look something like this:
[VerifyAccess(requireClientDashboardAccess: true, requireConnectedStripeAccount: false)]
[VerifyAccess(requireClientDashboardAccess: true, requireConnectedStripeAccount: false)]
nox7
nox74mo ago
I don't know why I locked out using constructor parameters from my mind. That's a good solution - thanks.