Hi,
We add many different azure functions project in the solution, we want to make the Authorization and Authentication (role and permission(AppPermission Consts) check) for users successfully injected in our azure functions project. And how can show that api url models in swagger or in another pages. So, how can we do that?
App Version : Core MVC 14.3
Thanks.
3 Answer(s)
-
0
Hi @tdv.yazilim
Token Based Authentication: You can verify the bearer token in your function by reusing ASP.NET Zero's JWT settings. This way, the token generated by your main application can also be verified within Azure Functions.
Authorization/Permission Controls: You need to add the same ABP services (such as IPermissionChecker, ICurrentUser) to your Azure Functions. To achieve this, register your function project as an ABP module (or a class library referenced by the function) so that it shares the IoC container with your application. Related Blog Post
Swagger Integration: Azure Functions does not provide Swagger support by default. You can use community packages like Swashbuckle for Azure Functions, or expose your APIs through your main API project and keep the Functions as internal logic. This way, your existing ASP.NET Zero Swagger UI will automatically display your API models and endpoints.
Therefore, the recommended approach would be:
You can use the same JWT authentication configuration in Azure Functions as in your main application.
You can reference your domain and application layer in the Functions project to access AppPermissionConsts and ABP authorization.
For API documentation, integrate a Swagger library for Functions or proxy these endpoints through your API module.
Markdown is supportedCopy & paste or drag & drop images (max 30 MB per image) -
0
Hi @oguzhanagir
First of all, thank you. I read the article. However, I'm getting an error Program.cs run. What could be the reason? My codes are below:
Module
using Abp.AspNetZeroCore; using Abp.Modules; using Abp.Reflection.Extensions; using Abp.Zero.Configuration; using Microsoft.Extensions.Configuration; using Company; using Company.EntityFrameworkCore; namespace MyFunc; [DependsOn( typeof(CompanyCoreModule) , typeof(CompanyEntityFrameworkCoreModule) )] public class MyFunctionsModule : AbpModule { private IConfigurationRoot _cfg; public MyFunctionsModule(CompanyEntityFrameworkCoreModule abpZeroTemplateEntityFrameworkCoreModule) { abpZeroTemplateEntityFrameworkCoreModule.SkipDbSeed = true; } public override void PreInitialize() { _cfg = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); Configuration.BackgroundJobs.IsJobExecutionEnabled = false; Configuration.UnitOfWork.Timeout = TimeSpan.FromMinutes(30); Configuration.UnitOfWork.IsTransactional = false; Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization(); var cs = _cfg.GetConnectionString("Default"); if (!string.IsNullOrWhiteSpace(cs)) Configuration.DefaultNameOrConnectionString = cs; var license = _cfg["AbpZeroLicenseCode"]; if (!string.IsNullOrWhiteSpace(license)) Configuration.Modules.AspNetZero().LicenseCode = license; } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(MyFunctionsModule).GetAssembly()); } }Program.cs
using Abp; using Abp.Authorization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MyFunc; var host = new HostBuilder() .ConfigureFunctionsWebApplication() .ConfigureAppConfiguration(cfg => { cfg.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); }) .ConfigureServices((ctx, services) => { try { var bootstrapper = AbpBootstrapper.Create<MyFunctionsModule>(); bootstrapper.Initialize(); services.AddSingleton(bootstrapper); services.AddTransient(_ => bootstrapper.IocManager.Resolve<IPermissionChecker>()); services.AddHttpClient(); } catch (Exception ex) { Console.WriteLine("ABP bootstrap failed in ConfigureServices: " + ex); throw; } }) .Build(); await host.RunAsync(); ------------------------------- Http trigger Function // Functions/GetCountriesFunction.cs using Abp; using Abp.Authorization; using Abp.Dependency; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System.Net; public class GetCountriesFunction : ITransientDependency { private readonly ILogger<GetCountriesFunction> _logger; private readonly IPermissionChecker _permissionChecker; private readonly IConfiguration _cfg; public GetCountriesFunction( ILogger<GetCountriesFunction> logger, IPermissionChecker permissionChecker, IConfiguration cfg) { _logger = logger; _permissionChecker = permissionChecker; _cfg = cfg; } [Function("GetCountries")] public async Task<HttpResponseData> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "regions/countries")] HttpRequestData req) { _logger.LogInformation("GetCountries called"); var principal = JwtHelper.Validate(req, _cfg); if (principal == null) return req.CreateResponse(HttpStatusCode.Unauthorized); var (userId, tenantId) = JwtHelper.GetIds(principal); if (userId is null) return req.CreateResponse(HttpStatusCode.Unauthorized); var user = new UserIdentifier(tenantId, userId.Value); var permission = Company.Authorization.AppPermissions.Pages_Administration; if (!await _permissionChecker.IsGrantedAsync(user, permission)) return req.CreateResponse(HttpStatusCode.Forbidden); var resp = req.CreateResponse(HttpStatusCode.OK); await resp.WriteAsJsonAsync(new[] { new { code = "TR", name = "Turkey" }, new { code = "US", name = "United States" } }); return resp; } } .csproj <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net9.0</TargetFramework> <AzureFunctionsVersion>v4</AzureFunctionsVersion> <OutputType>Exe</OutputType> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <FrameworkReference Include="Microsoft.AspNetCore.App" /> <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.23.0" /> <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.1.0" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="2.0.0" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.0.2" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.0.5" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\src\Company.EntityFrameworkCore\Company.EntityFrameworkCore.csproj" /> </ItemGroup> </Project> Console Error Log Exceeded language worker restart retry count for runtime:dotnet-isolated. Shutting down and proactively recycling the Functions Host to recoverMarkdown is supportedCopy & paste or drag & drop images (max 30 MB per image) -
0
Hi @tdv.yazilim
An explanation regarding the issue you mentioned has been sent via e mail.
Markdown is supportedCopy & paste or drag & drop images (max 30 MB per image)