I am preparing to port an .NET 4.6.1 application to .NET Core and struggle to find how the code permissions should be handled.
Currently i use custom ClaimsAuthorizationManager
public class AuthorizationManager : ClaimsAuthorizationManager
{
public override bool CheckAccess(AuthorizationContext context)
{
var resource = context.Resource.First().Value;
var action = context.Action.First().Value;
return context.Principal.HasClaim(resource,action);
}
}
The ClaimsAuthorizationManager is configured to be used by application in app.config file.
Then each function that needs to have a code access permission has an ClaimsPrincipalPermission set with required permissions.
Now i would want to achieve same functionality in .NET Core and outside of MVC.
Anyone has any idea if and how is this achievable?
Thanks.
Related
I've configured Live Metrics for my ASP.NET MVC app with target framework 4.7.2 using the tutorial given in Microsoft Docs:
https://learn.microsoft.com/en-us/azure/azure-monitor/app/live-stream#enable-livemetrics-using-code-for-any-net-application
In this tutorial, they've given a sample client.TrackDependency() and client.TrackRequest() call in the end. They've also mentioned in comments that those are samples and we must replace it with actual application logic to work. I'm new to all these and I don't know what to replace. Since my application is huge and has a lot of methods, it is impractical to call the tracking methods in each method or controller. Since it is not ASP.NET Core, there are no middlewares and I have to enable Live Metrics by code too. I've added the code in the Application_Start() of Global.asax.cs of my application, so that it runs during startup.
This is what I've done so far,
// Create a TelemetryConfiguration instance.
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration telemetryConfig = Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault();
telemetryConfig.InstrumentationKey = System.Web.Configuration.WebConfigurationManager.AppSettings["AppInsightsInstrumentationKey"];
QuickPulseTelemetryProcessor quickPulseProcessor = null;
telemetryConfig.DefaultTelemetrySink.TelemetryProcessorChainBuilder
.Use((next) =>
{
quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
return quickPulseProcessor;
})
.Build();
var quickPulseModule = new QuickPulseTelemetryModule();
// Secure the control channel.
// This is optional, but recommended.
//quickPulseModule.AuthenticationApiKey = "YOUR-API-KEY-HERE";
quickPulseModule.Initialize(telemetryConfig);
quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);
// Create a TelemetryClient instance. It is important
// to use the same TelemetryConfiguration here as the one
// used to setup Live Metrics.
TelemetryClient client = new TelemetryClient(telemetryConfig);
// I need some method by which I can track all the requests, exceptions,
// dependencies etc. here.
I searched and searched a lot for a solution but couldn't get a concrete solution. As a last resort I'm requesting you guys to help me. What can I do to track all requests, dependencies, exceptions, etc. globally...?
If you're using the ASP .NET MVC with .Net Framework 4.7.2 Version, You need to configure the Application Insights code related to the .NET Specific SDK Type like Framework, Core, Console, etc.
From the given MS doc, you're following the console app related app insights code but as you're using the MVC Web App so you need to follow this code from this section of documentation.
Here is the workaround I tried to get the live metrics, logs in the Application Insights of Azure Portal.
In Visual Studio, Created the asp .net mvc web app (.NET Framework version 4.7.2)
Added the Application Insights Instrumentation Key in the ApplicationInsights.config
Follow the above documentation as it says to create a new folder in the root and add the ErrorHandler class and modify the FilterConfig class from the App_Start folder in order to match your ErrorHandler Class Functionality.
And then deploy the MVC Web App. While publishing configure the Application Insights in Visual Studio Publish Window like below:
After deploying the App, Open the Web App URL in the browser, then you can see the logs in overview tab and also in App Insights Resource Live Metrics Page as you can see the screenshots below:
I found a solution myself. I found out that I can use the Application_BeginRequest() event handler to catch all requests inside Global.asax itself. All I had to do is to store the TelemetryConfiguration into a global variable and access it from the Application_BeginRequest() handler. This is what I did:
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
protected void Application_Start()
{
RegisterLiveMetrics();
// Omitted the other code for brevity
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var telemetryConfig = Application["TelemetryConfig"] as TelemetryConfiguration;
TelemetryClient client = new TelemetryClient(telemetryConfig);
var httpContextCurrent = HttpContext.Current;
client.TrackRequest(httpContextCurrent.Request.RawUrl, DateTimeOffset.Now,
TimeSpan.FromMilliseconds(230), httpContextCurrent.Response.StatusCode.ToString(),
true);
}
private void RegisterLiveMetrics()
{
// Create a TelemetryConfiguration instance.
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration telemetryConfig = Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault();
telemetryConfig.InstrumentationKey = System.Web.Configuration.WebConfigurationManager.AppSettings["AppInsightsInstrumentationKey"];
QuickPulseTelemetryProcessor quickPulseProcessor = null;
telemetryConfig.DefaultTelemetrySink.TelemetryProcessorChainBuilder
.Use((next) =>
{
quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
return quickPulseProcessor;
})
.Build();
var quickPulseModule = new QuickPulseTelemetryModule();
quickPulseModule.Initialize(telemetryConfig);
quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);
Application["TelemetryConfig"] = telemetryConfig;
}
Luckily this seems to work fine. Currently I'm only tracking requests.
Note: I'm not sure about the namespaces mentioned above.
As the title says,
How can I set up a middleware in a .NET Core 3.1 Azure Functions project? trying to dependency inject an external service that requires middleware.
First off, there are some problems here.
The Function app you create in Visual Studio 19, doesn't contain a Startup.cs class.
So we have to create this manually. Then there's a problem that it's not behaving like a real Startup class. It needs to inherit FunctionsStartup.
This is achieved by adding this line of code before the namespace first for some reason.
[assembly: FunctionsStartup(typeof(test_project.Startup))]
Then we need to inherit FunctionsStartup and then implement it.
public override void Configure(IFunctionsHostBuilder builder)
{
}
So after this, we are able to Add stuff like Singleton or external service like so,
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSomeExternalService();
builder.Services.AddSingleton<SomeOtherStuff>(
new SomeOtherStuff(config, env_SomeOtherStuff));
}
But now my real problem starts. We need to add middleware for some functionality to work in the external service.
Usually, you can do this in a web applications (not function app) like so,
public void Configure(IApplicationBuilder app)
{
app.UseSomeExternalServiceMiddleware();
}
The problem is, I can't figure out how to do this in a function app with core 3.1
maybe it's not implemented the same way, I don't know why.
Is there a workaround for this sort of problem?
There is no direct way to do this but there is a proposed feature that you can refer to.
More References :
Dependency Injection in Azure Functions with C# (twilio.com)
c# - Azure Functions Runtime v3 Middleware - Stack Overflow
Be able to overwrite http response in IFunctionsWorkerMiddleware · Issue #530 · Azure/azure-functions-dotnet-worker · GitHub
So I've been using the following code to get windows user-name within my .NET Core 2 web applications. However, I'm trying to use the same method in .NET Core 3 and it works, but periodically it will just stop working and I have to restart the application in order for it to start working. I'm not sure whether it's a timeout or something else.
Here's the code that I'm using within my Authentication controller
AuthController.cs
public AuthController()
{
}
[Authorize]
public override void OnActionExecuting(ActionExecutingContext context)
{
var userName = User.Identity.Name;
}
Like I said before, this usually works fine. But on occasion it stops working completely till I restart the application. The issue I get is a NullReferenceException on the User object itself. Is there something new in .NET Core 3 or is there something that I'm just completely missing here?
Thanks
I'm currently trying to integrate postsharp with my asmx web service for the purpose of logging exceptions.
Here's my code for the Aspect perspective:
[Serializable]
public class LogPerformance : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
string test = "test";
base.OnEntry(args);
}
public override void OnExit(MethodExecutionArgs args)
{
string test = "test";
base.OnExit(args);
}
public override void OnException(MethodExecutionArgs args)
{
string test = "test";
base.OnException(args);
}
}
while in my Service.cs class, i've the following web method:
[WebMethod(EnableSession = true)]
[SoapHeader("authentication")]
[LogPerformance]
public DataTable loginUser(string userName, string password)
{
doStuff();
}
Coming straight to the point:
Does postsharp support implementation with web methods? As in my case,
postSharp methods does not get called whenever the web method receives
a hit. (Yes i've added postsharp reference using Nuget and/or/plus manually added its dll as well) This does
suggest a step towards the mentioned subject but i could not make anything
out of it.
It is important to note that the same LogPerformance Class runs smoothly when integrated with:
Web API
ASP.Net Web Application (MVC)
Console Application
The problem is when i use it with .asmx web service. A little nudge towards the right direction would be appreciated.
The *.asmx web-services are supported by PostSharp. However, you need to pay attention whether your ASP.NET project is a Web Site or a Web Application (ASP.NET Web Site or ASP.NET Web Application?). Only Web Application projects are supported by PostSharp. For more information on compatibility you can also check Requirements and Compatibility.
You can convert your Web Site project to Web Application project by following the guidelines from the blog post Converting a Web Site Project to a Web Application Project. After the conversion you need to install PostSharp NuGet package into your project.
I am trying to take the github ServiceStack.UseCases/ImageResizer project, and make it self hosted. I thought this would be really easy, so I referenced this: https://github.com/ServiceStack/ServiceStack/wiki/Self-hosting but AppSelfHostBase is undefined in the project. I then tried AppHostHttpListenerBase and that got me to the point where I could at least hope to setup my self host:
public class AppHost : AppHostHttpListenerBase
{
public AppHost() : base("Image Resizer", typeof(AppHost).Assembly) {}
public override void Configure(Container container) {}
}
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
AppHost appHost = new AppHost();
appHost.Init();
appHost.Start("http://*:1301/");
}
}
I then transferred the project over to my CentOS box with mono. In monodevelop I was able to build and run, but it failed during runtime. It appears it still thinks it is an Mvc or Asp.Net project.
Aside from this attempt, I have a working self hosted ServiceStack project running there, but it is not this ImageResizer and all attempts to get my existing project to include the new project have also failed.
I also tried to include code that was part of the working self hosted project into the new one, but then symbols are undefined. Basic symbols like "ServiceStackHost". If I start trying to use Nuget and do more "Install-Package" I can solve this symbol problem, but then just cause other symbols that used to be resolved to no longer work. I don't really fully understand Nuget. Any ideas for a way forward would be appreciated.
ServiceStackHost and AppSelfHostBase are new classes added in ServiceStack v4.
You can use AppHostHttpListenerBase which is a Self-hosting class in ServiceStack v3. You're looking at the v4 docs, here are the docs for ServiceStack v3 which for Self-Hosting is at:
https://github.com/ServiceStackV3/ServiceStackV3/wiki/Self-hosting
Self-Hosting apps are normally created in a Console Application where-as your example is trying to run a self-hosting app inside an ASP.NET Web Application. If you want to run ServiceStack in an ASP.NET app you should inherit AppHostBase, otherwise if you want to run a self-hosting application, create a new Console Application and inherit from AppHostHttpListenerBase.