Home > Net >  Common function called on every action
Common function called on every action

Time:02-18

I have an ASP.NET Core web service running on Azure AppService. With every REST call, I check the auth0 token against my profile table to double-check they are a valid user.

Is there a way of refactoring this code out of every REST call, so it always run for every ASP.NET Core call coming in?

Here is a typical example of a REST call... (there are about 30 in all)

[Authorize]
[HttpGet("accounts/{accountId}")]
public async Task<ActionResult<ArchiveJob>> AccountGet(int accountId) 
{
   //--- common code repeated in every function
   var profile = await RetrieveProfile();

   if (profile is null) 
   {
      return NotFound("Profile not found for this user")
   }

   // ... rest of function
   return Ok();
}

CodePudding user response:

The right way, is to use AddAuthorization to define your authorisation policies. Perhaps changing the default policy;

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .RequireAssertion(context => {
            // note; https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-6.0#access-mvc-request-context-in-handlers
            if (context.Resource is HttpContext c)
            {
                var something = c.RequestServices.GetRequiredService < ...> ();
                var profile = await something.RetrieveProfile();
                if (profile != null)
                    return true;
            }
            return false;
        })
        .Build();
});

CodePudding user response:

You can create a IAuthorizationFilter to create a custom filter in your core application so it always runs for every ASP.NET Core call coming in.

public class MyAuthAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //check access 
        if (CheckPermissions())
        {
            //all good, add some code if you want. Or don't
        }
        else
        {
            //DENIED!
            //return "ChallengeResult" to redirect to login page (for example)
            context.Result = new ChallengeResult(CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}

you can also find detail here

  • Related