1

I want to store my credential in redis cache for authentication. For that I created the filter. But I could not use(inject) the IDistributedCache in filter.

public class Authorization : AuthorizeAttribute,IAuthorizationFilter
{
    IDistributedCache distributedCache;
    public void OnAuthorization(AuthorizationFilterContext filterContext)
    {
        //Authentication

        bool skipAuthorization = filterContext.Filters.Any(item => item is IAllowAnonymousFilter);
        if (skipAuthorization)
        {
            return;
        }
        try
        {

            string token = distributedCache.GetString("TokenValue");
            if (token == null)
            {
                // unauthorized!
                filterContext.Result = new UnauthorizedResult();
            }
        }
        catch (InvalidOperationException)
        {
            filterContext.Result = new UnauthorizedResult();
        }
    }
}

If I generate constructor for above class and inject the IDistributedCache in constructor then I got an error while using that filter

So is there any another way to use redis cache in filters?

Tejas
  • 381
  • 1
  • 7
  • 25

1 Answers1

1

Sure you can generate a constructor and IDistributedCache as a parameter

Then you can register filter for an action like this: [TypeFilter(typeof(Authorization))]

Code sample:

[HttpGet]
[TypeFilter(typeof(AuthorizationFilterAttribute))]
public ActionResult<IEnumerable<string>> Get()
{
    return new string[] { "value1", "value2" };
}
Khai Nguyen
  • 935
  • 5
  • 17