ASP.Net Core 2.0 Webapi set log4net - log4net

I am new to asp.net core 2.0. I creating a webapi and want to configure log4net as my logging provider.
I couldn't find some working example in net. Can anyone help me provide the right link or some sample code about how to properly setup log4net in asp.net core 2.0
Things i have done so far is as below and i am not sure how to proceed further.
installed log4net.Extensions.AspNetCore;
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddLog4Net();
// Enable CORS
app.UseCors(builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseMvc();
}

Install nuget for Microsoft.Extensions.Logging.Log4Net.AspNetCore (https://www.nuget.org/packages/Microsoft.Extensions.Logging.Log4Net.AspNetCore/)
In Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) call loggerFactory.AddLog4Net();
Create log4net.config
More info -> https://github.com/huorswords/Microsoft.Extensions.Logging.Log4Net.AspNetCore

Related

Azure AD Login issue only happening when running app on IIS Server

I've got a small Blazor app that uses AzureAD for user authentication. When I run the app directly from visual studio, I am able to login without any issues, however when I deploy the app to IIS, I get the below error when I click 'Login'.
IOException: IDX20807: Unable to retrieve document from: 'System.String'. HttpResponseMessage:
'System.Net.Http.HttpResponseMessage', HttpResponseMessage.Content: 'System.String'.
Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string address,
CancellationToken cancel)
InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'.
Microsoft.IdentityModel.Protocols.ConfigurationManager<T>.GetConfigurationAsync(CancellationToken cancel)
My appsettings.json configuration is:
AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "qualified.domain.name",
"TenantId": "22222222-2222-2222-2222-222222222222",
"ClientId": "11111111-1111-1111-11111111111111111",
"CallbackPath": "/signin-oidc",
"ClientSecret": "NNNNNNN-~nnnnnnnn_NNNNNNNNNNN~nnnn"
},
With the Domain, TenantId, ClientId and ClientSecret being populated from the secrets.json file.
My ConfigureServices function in the Startup.cs is:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(options =>
{
Configuration.Bind("AzureAd", options);
}, GraphConstants.Scopes)
.AddInMemoryTokenCaches();
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
services.AddRazorPages();
services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
services.AddMudServices();
}
And the code for the Login button is:
<AuthorizeView>
<Authorized>
Hello, #context.User.Identity.Name!
Log out
</Authorized>
<NotAuthorized>
Log in
</NotAuthorized>
</AuthorizeView>
My IIS configuration was done following the steps in this tutorial - https://www.c-sharpcorner.com/article/deploying-a-blazor-application-on-iis/
I've tried playing around with different settings around the AddMicrosoftIdentityWebApp section, figuring it was something to do with the configuration there, but nothing I try seems to make any difference.
Any help would be appreciated,
Thanks
Turns out the issue was to do with me using secrets.json to store some of the configuration.
This thread - ASP.NET Core 2 web application isn't loading user secrets when debugging IIS website - helped me figure out the solution

How to acquire a token with Azure AD and MSAL in ASP.NET

I'm trying to authenticate a token using Azure AD. In a console application, I have no problem with this thanks to IConfidentialClientApplication:
static void Main(string[] args)
{
Console.WriteLine("Making the call...");
RunAsync().GetAwaiter().GetResult();
}
private static async Task RunAsync()
{
AuthConfig config = AuthConfig.ReadJsonFromFile("appsettings.json");
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
string[] ResourceIds = new string[] { config.ResourceId };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(ResourceIds).ExecuteAsync();
}
...
}
But in a Startup for an ASP.NET Core application, the app uses the standard IApplicationBuilder and the Configure(...) method can't take an IConfidentialClientApplicationBuilder as it doesn't exist.
In Microsoft's documentation, they create a PublicClientApplicationBuilder, but I don't want to start creating entirely new applications in my configuration.
Here is a sample of Startup for ASP.NET Core application for your reference. But as far as I know we can't get token directly in the Startup for ASP.NET Core application with "IApplicationBuilder". "IApplicationBuilder" and "IConfidentialClientApplicationBuilder" are two different concepts.
For your requirement, you can just import modules for msal and use the code you provided above or the code you mentioned in the Microsoft's documentation to get the token.

How to set a custom json IIS error messages in Azure Web App

I have a ASP.NET Core 2.1 (API) application running in Azure Web App.
My application errors follow a standard json structure. When there is an error (for example a 500) in IIS, it returns a xhtml page with the description of the error.
How can I set Azure Web App, or my application, so that on IIS errors, it returns a json string defined by me.
Thanks in advance.
We can use this method to achieve this: IApplicationBuilder.UseStatusCodePagesWithRedirects()
Here is a sample for your reference:
We can create Controller to handle the error output:
[Route("Home/Error/{statusCode}")]
public IActionResult Error(int statusCode)
{
JsonResult jsonResult = new JsonResult(new object());
return jsonResult;
}
Then We can use it in Configure(IApplicationBuilder app, IHostingEnvironment env) as below:
app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");
Hope this would be helpful to you.

Secure asp.net core 2.0 webapi with Identityserver3

I am completely new to Identityserver and authorization.
There is an authorization server build using Identityserver3. It works fine with asp.net mvc 5 application.
Now i am trying to use this authorization server to secure the new asp.net core 2.0 webapi.
I couldn't find any good document about how to do this. Can anyone help how to do achieve this?
Thanks
The same way as you will do it if you use IdentityServer 4. In your .NET Core 2.0 Web API, in the Startup.cs :
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "<identityserverurl>";
options.RequireHttpsMetadata = false;
options.ApiName = "mynetcoreapi";
});
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseMvc();
}
}
and of course you need IdentityServer4.AccessTokenValidation package, but it is a .NET Core package, so you shouldn't have any problems.
PS: Don't forget to setup logging (if it is not already done) in your IdentityServer. Helps a lot

Using Owin in .Net Core for 3rd Party Authentication

I am trying to use third party sign on authentication in a .net core web application solution I am creating. I am trying to use the Owin package to do so. I have looked at an example of Owin in .net framework, I have been trying to translate this to the .net core application but I have been very unsuccessful.
If someone could point me to an example of a .net core web application that is using Owin for 3rd party authentication it would be greatly appreciated.
Here is the the startup file for a framework web application:
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Facebook;
using Microsoft.Owin.Security.Google;
using Owin;
[assembly: OwinStartupAttribute(typeof(Identity.Startup))]
namespace Identity
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
/* app.UseTwitterAuthentication(
consumerKey: "",
consumerSecret: "");*/
app.UseFacebookAuthentication(
appId: "myid",
appSecret: "mysecret");
//app.UseGoogleAuthentication();
}
}
I Want to replicate this in .net core now. However, I cannot reproduce the Microsoft.Owin.Security dependency. I have tried Microsoft.AspNetCore.Owin.Security and it does not resolve.

Resources