Autofac,授权过滤器和WebApi 2

时间:2017-04-28 22:35:10

标签: c# asp.net-web-api2 autofac

我有一段时间没有这个问题,我无法确定这是否真的是一个问题。

我有一个控制器方法,其目的是将文档添加到文档列表中:

[Route("Documents/DocumentLists/{documentListId:int}")]
[HttpPost]
public async Task<IHttpActionResult> Add() {
    CreateDocumentCommand createCommand = null;
    IHttpActionResult actionResult = null;

    // Check if the request contains multi-part/form-data.
    if(!Request.Content.IsMimeMultipartContent()) {
        return new SimpleErrorResult(Request, HttpStatusCode.UnsupportedMediaType, "Form is not multi-part.");
    }

    try {
      var data = await Request.Content.ParseMultipartAsync();

    .....code ellided

我正在使用Autofac注册方法:

builder.RegisterType<DocumentListAdminAuthorizationFilter>().AsWebApiAuthorizationFilterFor<DocumentsController>(c => c.Add()).InstancePerLifetimeScope();

因为控制器方法有async关键字,所以我不断收到警告:

“因为没有等待此调用,所以在调用完成之前会继续执行当前方法”

但是,代码可以正常工作,不在相应角色中的用户无法访问该方法。具有相应角色的用户可以添加文档。

我并不完全理解一切如何在幕后工作,以便一切正常运作。

已编辑 - 2017-05-01

我本身并没有收到错误。我收到了警告。代码编译和工作。

以下是过滤器:

public class DocumentListAdminAuthorizationFilter : IAutofacAuthorizationFilter {
    readonly IDocumentListContainerRepository documentListRepository;
    readonly IUserRepository userRepository;
    readonly IWebUserSession userSession;
    readonly ILog logger;
    readonly IPeotscConfigurationSection configuration;
    readonly IMediator mediator;

    /// <summary>
    /// Initializes a new instance of the <see cref="DocumentListAdminAuthorizationFilter"/> class.
    /// </summary>
    /// <param name="userSession">The user session.</param>
    /// <param name="userRepository">The user repository.</param>
    /// <param name="documentListRepository">The document list repository.</param>
    public DocumentListAdminAuthorizationFilter(ILog logger, IWebUserSession userSession, IPeotscConfigurationSection configuration,
        IUserRepository userRepository, IDocumentListContainerRepository documentListRepository, IMediator mediator) {
        this.userSession = userSession;
        this.userRepository = userRepository;
        this.documentListRepository = documentListRepository;
        this.logger = logger;
        this.configuration = configuration;
        this.mediator = mediator;
    }

    /// <summary>
    /// Called on authorization.
    /// </summary>
    /// <param name="actionContext">The action context.</param>
    /// <exception cref="InvalidResourceRequestHttpRequestException"></exception>
    /// <exception cref="NotAuthorizedHttpRequestException"></exception>
    public void OnAuthorization(HttpActionContext actionContext) {
        int documentListId = 0;
        User user = null;

        if(!Check.CanGetInteger(actionContext.RequestContext.RouteData.Values["documentListId"], out documentListId)) {
            throw new InvalidResourceRequestHttpRequestException();
        }

        if(Check.NotNull<IWebUserSession>(userSession) && Check.NotEmpty(userSession.UserName)) {
            throw new SessionHasExpiredHttpRequestException();
        }

        user = userRepository.GetUserByUserName(userSession.UserName);

        if(ReferenceEquals(null, user)) {
            throw new UserNotFoundHttpRequestException();
        }

        var documentList = documentListRepository.GetById(documentListId);

        if (ReferenceEquals(null, documentList)) {
            throw new DocumentListNotFoundHttpRequestException();
        }

        var isTemplateAdmin = userRepository.IsDocumentListAdmin(user, documentList);

        if(!isTemplateAdmin) {
            Exception exception = new Exception("User attempted to access administrator functionality on the document list to which they should not have had access.");
            exception.Data.Add("UserId", user.Id);
            exception.Data.Add("UserName", user.UserName);
            exception.Data.Add("DocumentListId", documentList.Id);
            logger.Error("Inappropriate access to document list functionality.", exception);

            InappropriateAdministratorAccessEmailSendEvent eventMessage = new InappropriateAdministratorAccessEmailSendEvent {
                User = user,
                DocumentList = documentList
            };

            mediator.Publish(eventMessage);

            throw new NotAuthorizedHttpRequestException();
        }
    }

    public Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken) {
        OnAuthorization(actionContext);
        return Task.FromResult<object>(null);
    }
}

0 个答案:

没有答案