Open Closed

Resolving injection issue of AppService into InvokeAsync in Middleware #6807


User avatar
0
dev@veek.vn created

Hello,

I have added the ApiKeyMiddleware to filter the API and ensure that the request has the necessary API key to pass. In the InvokeAsync method, how can I inject the IPartnersAppService to retrieve the partner from the database for verification?

using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace AA.Core.BackOffice;

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string APIKEY = "key";
    private readonly ILogger _logger;

    public ApiKeyMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger<ApiKeyMiddleware>();;
    }
    
    public async Task InvokeAsync(HttpContext context) {
        await LogRequestBody(context);

        if (!context.Request.Query.TryGetValue(APIKEY, out
                var extractedApiKey)) {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Api Key was not provided ");
            return;
        }
        
        var appSettings = context.RequestServices.GetRequiredService < IConfiguration > ();
        var apiKey = appSettings.GetValue < string > ("App:AhamoveApiKey");
        if (apiKey == null || !apiKey.Equals(extractedApiKey)) {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Unauthorized");
            return;
        }
        await _next(context);
    }

    private async Task LogRequestBody(HttpContext context)
    {
        context.Request.EnableBuffering();
        string requestBody = await new StreamReader(context.Request.Body, Encoding.UTF8).ReadToEndAsync();
        context.Request.Body.Position = 0;
        _logger.LogInformation("Request Body: {RequestBody}", requestBody);
    }
}

ABP Framework version: v.7.3.2 UI Type: Angular Database System: MongoDB Tiered (for MVC) or Auth Server Separated (for Angular): yes Exception message and full stack trace: Steps to reproduce the issue:


3 Answer(s)
  • User Avatar
    0
    dev@veek.vn created

    i have tried like this but not work

    private readonly IPartnersAppService _partnerService;
    
        public ApiKeyMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IPartnersAppService partnerService)
        {
            _next = next;
            _partnerService = partnerService;
            _logger = loggerFactory.CreateLogger<ApiKeyMiddleware>();;
        }
    
  • User Avatar
    0
    dev@veek.vn created

    exception is Exception of type 'Volo.Abp.Authorization.AbpAuthorizationException' was thrown. when I call await _partnerService.GetAsync(Guid.NewGuid());

  • User Avatar
    0
    dev@veek.vn created

    I added the [AllowAnonymous] attribute to the service and it worked! :)))

    closed this question

Made with ❤️ on ABP v9.1.0-preview. Updated on December 13, 2024, 06:09