LazyCoder7
LazyCoder7

Reputation: 45

Skip a MediatR Behavior Pipeline

I have been using MediatR Pipelines to do the following things (in the same order)

  1. Add the current login user's claims.
  2. Authorize the User based on the set of claims.
  3. Validate the Input Model
  4. Performance tracking Pipeline Behavior.

For steps 1 and 2. I have my MediatR Objects inherited from a class called Request which looks like this.

public class Request
    {
        /// <summary>
        /// Gets or sets the current login user.
        /// </summary>
        [JsonIgnore]
        public ClaimsPrincipal User { get; set; }
    }

Here is a sample MediatR Query Object.

 public class GetById : Request, IRequest<CompanyViewModel>
    {
        /// <summary>
        /// Gets or sets the Company Id.
        /// </summary>
        public int CompanyId { get; set; }
    }

Here is my pipeline behavior for 1) in which I inject IHttpContextAccessor and get the Claims.

public class AttachContextUserPipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : Request

Here is the pipeline behavior for 2) In which I authorize the user.

public class AuthorizationPipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
        where TRequest : Request

This was fine until now but I now have few of my Query/Command objects which does not require authorization (kind of allow anonymously). But in this scheme of things I have to inherit the Query/Command class from Request and also have an Authorization Pipeline Handler defined. Otherwise, Exceptions are raised.

How can I have this scheme of things as it is and just skip/jump the authorization pipelines and just directly fire the MediatR command so that it handler is called and it skips the authorization handler in between?

Upvotes: 1

Views: 1706

Answers (1)

Philip Nunn
Philip Nunn

Reputation: 41

A little late but what I just did was create a SkipAuthorizationAttribute and add it to my request.

  [AttributeUsage(AttributeTargets.Class)]
  public class SkipAuthorizationAttribute : Attribute
  {
  }

  [SkipAuthorization]
  public class Request
  {
    /// <summary>
    /// Gets or sets the current login user.
    /// </summary>
    [JsonIgnore]
    public ClaimsPrincipal User { get; set; }
  }

Then in the behavior, I checked for the attribute and skipped if found.

    private bool ShouldSkip() =>
  Attribute.GetCustomAttribute(typeof(TRequest), typeof(SkipAuthorizationAttribute)) != null;

Upvotes: 4

Related Questions