Integrate OpenIDConnect into Classic ASP app - asp.net

We have a legacy application built in Classic ASP that needs to access an API - this API is "protected" by an IdentityServer - so basically we need to implement OpenIdConnect support for this legacy application.
By far the easiest solution I can think of is trying to wrap this site somehow in a more updated version, then we could just add a few lines of code in the Owin-startup and everything should(?) be fine by adding:
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("api1");
options.Scope.Add("offline_access");
});
So it is possible to somehow get OWIN to work with Classic ASP? Or are we doomed to try and built our own client/middleware?

If there is no other "show-stopper" preventing you to update to .Net Framework 4.5.1+, than this is your right solution.
If you go to the Owin official NuGet page it will show you, that the library particularly has no dependencies, BUT this is not quite correct.
If we go to the source of the Microsoft.Owin we will see:
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
So it actually depends on .Net Framework 4.5.1. If you have the possibility to upgrade your project - do it.

Related

What is the .NET Core way of storing application settings?

I'm developing a cross-platform (win/mac/linux) application and I'm looking to store my application state. What is the .NET Core recommended way of doing this?
I've dug through the documentation and the closest thing I found was this, which is aimed at Visual Studio/.NET Framework (and I'm on VS Code).
There are 3 ways,
ONLY For Localhost
Simply stash them in your appsettings.json or as environment
variables.
For Staging / Production,
Azure Key Vault
By utilising Azure Key Vault and the Microsoft.Extensions.Configuration.AzureKeyVault NuGet Package, you will be able to stash configurations for your projects in the best way possible in the actual environment.
You then simply inject it in,
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var root = config.Build();
config.AddAzureKeyVault(
$”https://{root["KeyVault:Vault"]}.vault.azure.net/",
root[“KeyVault:ClientId”],
root[“KeyVault:ClientSecret”]);
})
.UseStartup<Startup>();
Although you still have to stash those 3 variables in, Azure has Azure AD to enforce access only to specified Applications. Thus, you need to register an application under the Azure AD in order for this to work. There are also restrictive features that will help you sandbox Azure Key Vault further.
Existing Vault Storages
Last but not least, the last way is to utilise existing vault storage options like HashiCorp. Libraries like https://github.com/rajanadar/VaultSharp will help you to implement it quickly and effectively. This is suitable for you if you primarily use a non-Azure provider for your servers.
As described here, you can use appsettings.json, which is generated and referenced within the new project template in dotnet new command
You can use the ConfigurationBuilder from the Microsoft.Extensions.Configuration nuget package
Although the docs are for ASP Core, you should be able to use them in your regular .Net Core app.
Create settings.json:
{
"mysetting": "value",
}
And use it:
var configuration = new ConfigurationBuilder()
.AddJsonFile("settings.json")
.Build();
// get the values from the settings.json
var mySetting = configuration["mysetting"];
Console.WriteLine(mySetting);

How to setup ElmahCore for a Console Application?

I want to log errors for a console application using Elmah.I've found ElmahCore and elmah.io.core but I don't know how to setup any of them on a console app.I'm using .net core.
ELMAH (the open source project) doesn't work with .NET Core. ElmahCore has a lot of dependencies to ASP.NET Core, but if you really wanted to, you could do something like this:
class Program
{
static void Main(string[] args)
{
var log = new MemoryErrorLog();
log.Log(new Error(new Exception()));
var errors = new List<ErrorLogEntry>();
var result = log.GetErrors(0, 10, errors);
Console.WriteLine(result);
Console.WriteLine(errors);
Console.ReadLine();
}
}
You can replace MemoryErrorLog with a target logger of your choice.
The package named elmah.io.core is a deprecated package from elmah.io. elmah.io is (among other things) a commercial cloud version of ELMAH, where you store all of your errors in the cloud (list of differences between ELMAH and elmah.io). elmah.io works with .NET core through either the Elmah.Io.Client NuGet package or using one of the integrations for popular logging frameworks like Serilog and NLog.
I wouldn't recommend you to use ElmahCore for logging in a console application. It is created for ASP.NET Core. There are much better options for logging from a console application, like the mentioned logging frameworks.

Application Insights and Asp.Net core Configuration

I keep reading about the importance of configuring ApplicationInsights to reduce unwanted traffic and other things.
How do I do that in an Asp.Net Core application? There doesn't seem to be an applicationinsights.config XML file anymore.
I can see a ConnectService.json file in the Application Insights folder, but there isn't much in it?
How do I configure AI for an Asp.Net Core application?
Anyone have links to docs? I can't seem to find any...
TIA
All of this is now in code, and mostly documented on the application insights asp.net core github wiki.
for example, see https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Dependency-Tracking-and-Performance-Counter-Collection where it has
Disabling Telemetry Module Services
In order to disable the services,
you need to manually remove the modules from the existing list of
services in the method ConfigureServices. Please note that telemetry
modules should be removed only after adding Application Insights to
the services.
// Removing dependency tracking telemetry module - to disable default dependency tracking
var dependencyTrackingService = services.FirstOrDefault<ServiceDescriptor>(t => t.ImplementationType == typeof(DependencyTrackingTelemetryModule));
if (dependencyTrackingService!= null)
{
services.Remove(dependencyTrackingService);
}
// Removing performance collector module - to disable default performance counter collection
var performanceCounterService = services.FirstOrDefault<ServiceDescriptor>(t => t.ImplementationType> == typeof(PerformanceCollectorModule));
if (performanceCounterService != null)
{
services.Remove(performanceCounterService);
}

Method not found: 'Newtonsoft.Json.JsonSerializerSettings Microsoft.AspNet.Mvc.MvcJsonOptions.get_SerializerSettings()'

Locally my project runs fine but when I deploy on Azure using a web app, I get the following error when it starts:
MissingMethodException: Method not found: 'Newtonsoft.Json.JsonSerializerSettings Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter.get_SerializerSettings()'.
SmartAdmin.Startup.<>c.b__13_7(MvcOptions options)
I've tried this:
services.AddMvc(options =>
{
options.Filters.Add(new UserPreferencesLoaderAtrribute());
var jsonFormatter = (JsonOutputFormatter)options.OutputFormatters.FirstOrDefault(f => f is JsonOutputFormatter);
if (jsonFormatter != null)
{
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
});
And this:
services.AddMvc(options =>
{
options.Filters.Add(new UserPreferencesLoaderAtrribute());
}).AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Yes, I just worked all night and did eventually figured it out. Here is what you need to do:
Make sure you install:
-Microsoft.AspNet.Mvc.Formatters.Json version "6.0.0-rc1-final"
and
-Revert Netonsoft.Json to "6.0.6".
Then you can keep this:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
project.json:
"Microsoft.AspNet.Mvc.Formatters.Json": "6.0.0-rc1-final",
"Newtonsoft.Json": "6.0.6"
I had a bunch of trouble redeploying too but eventually this worked.
Good luck!
Just got off a call with Microsoft support as of yesterday (02 Aug 2016) Azure App Services now only support ASP.NET core, due to a breaking change:
A breaking change was released and anything other than ASP.NET core is not supported, so the only option is an upgrade. The breaking change is being rolled out to all (regions) eventually all your instances will fail.
Is ASP.NET 5, Core RC1, RC2 supported on Azure App Service? NO
https://blogs.msdn.microsoft.com/waws/2016/06/14/supporting-asp-net-5-core-rc1-on-azure-app-service/
Verify your app is running the latest version of ASP.NET Core and not RC1 or RC2.
We were affected (North Europe) and upgraded our app from RC2 and it worked first time.
We also saw this in production, contacted the team and got this out: https://social.msdn.microsoft.com/Forums/en-US/f0a6bbaf-498a-4c1f-b869-6779ee18e04e/app-service-applications-may-experience-methodnotfound-exceptions-due-to-incorrect-newtonsoft-json?forum=windowsazurewebsitespreview
It appears that a fix for App Service is on its way as well. Meanwhile, the linked post contains pretty much the same instructions as the other answers here.

Why localization is not working as expected

I have an ASP .NET 5 RC1 website to which I am trying to add localization.
Based on the information found I did the following
In the ConfigureService in Startup.cs:
Enable Localization and setting the ResourcePath to "Resources"
Enable View Localization and Enable Data Annotations Localization
//check http://damienbod.com/2015/10/21/asp-net-5-mvc-6-localization/
services.AddLocalization(options => options.ResourcesPath = "Resources");
// Add MVC services to the services container.
//check http://blogs.msdn.com/b/webdev/archive/2015/10/15/announcing-availability-of-asp-net-5-beta8.aspx
services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization();
In the Configure method fin Startup.cs
Setup the list of supported cultures
Enable Request Localization
//check http://www.jerriepelser.com/blog/setting-thread-culture-aspnet5
//check http://damienbod.com/2015/10/21/asp-net-5-mvc-6-localization/
List<CultureInfo> supportedCultures = new List<CultureInfo>()
{
new CultureInfo("en"),
new CultureInfo("es")
};
var requestLocalizationOptions = new RequestLocalizationOptions()
{
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
app.UseRequestLocalization(requestLocalizationOptions, new RequestCulture(new CultureInfo("es")));
Create a Resources folder under the project
Create the Resources for the Controller. With the convention {Project}.{Controllers}.{ControllerClassName}.{culture}.resx
Create the Resources for the Views. With the convention Views.{ViewFolder}.{ViewName}.cshtml.{culture}.resx
Use the IHtmlLocalizer in the controller, and access the item. In this case localizer["Title"], which is found and works just fine. However when the culture is set to "es" it is not found and just falls back to the default resource.
private IHtmlLocalizer<HomeController> _htmlLocalizer;
public HomeController(IOptions<PTIWebPortal.Configuration.PTIWebPortalConfiguration> pConfiguration,
ILoggerFactory factory, IHtmlLocalizer<HomeController> localizer) : base(pConfiguration, factory)
{
this._htmlLocalizer = localizer;
}
The same is happens for the views, it only works with the default resource, but not with the others.
Any ideas on how to fix it?
There are a lot of known issues of things not working for localization as of rc1.
Some of the known issues are tooling related, so some of the localization things work if you run the app from the command line instead of launching from visual studio.
But even from the command line a lot of things that were supposed to work do not work.
There has been quite a bit of work after rc1 and a lot of localization issues have been fixed and closed recently, so things should be much better after rc2 is released sometime in February.

Resources