Programmatically modify WIF service configuration in .NET 4.5 - asp.net-mvc-4

Using WIF with .NET 4.5 in MVC4 app with Ninject
Here's the situation - I have a custom ClaimsAuthenticationManager subclass called TenantAccessClaimsAuthenticationManager that does some claims transformation. The TenantAccessClaimsAuthenticationManager needs a IRepository object to be injected into it (using ninject).
The .NET 4.5 impl of WIF suggests that I can stick my custom claims authentication manager in the web.config - however, this approach can only instantiate the object via a no-args ctor.
The second approach I had is to not have anything int the web.config, but in App_start, get a handle to the WIF configuration and stick in the TenantAccessClaimsAuthenticationManager in RegisterServices
How do I get a handle to the currently application's WIF configuration context? MSDN docs aren't helping.
Edit: Obviously the problem is that the onServiceConfigurationCreated event is no longer available. What's the best way to do this now

The event is still available!
code://System.IdentityModel.Services:4.0.0.0:b77a5c561934e089/System.IdentityModel.Services.FederatedAuthentication/event:FederationConfigurationCreated:System.EventHandler
More specifically, the event is available at FederatedAuthentication.FederationConfigurationCreated. An example implementation is below:
FederatedAuthentication.FederationConfigurationCreated += (sender, e) => {
e.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager = new MyCustomClaimsAuthenticationManager();
}
There's a blog post at http://dunnry.com/blog/2012/12/20/SettingClaimsAuthenticationManagerProgrammaticallyInNET45.aspx with more information.

Related

ASP.NET Transfer data from controller action

There is a sales service implemented as a Telegram bot. I need to create a website control panel for this service. Since the service is a .NET application I am thinking to use ASP.NET Core technology.
How do I transfer data from the controller action to the Program class containing all the functionality of the service (maybe it is worth defining the Program as a static class)?
You may have misunderstood Asp.Net Core. .net core adopts the pipeline mode, that is, when you call the action in the controller, it will enter the middleware pipeline of Program.cs(.net 5 is Startup.cs), and execute in sequence according to the order of your middleware, adopting the principle of first in, last out. This means that if you follow the normal .net core logic, the value you get in the controller (except the parameters defined in the URL), you cannot pass it into Program.cs. When you successfully enter the action of the controller, Program.cs has been executed.
Not sure what your sales service looks like, but I think you can register it as a service and use it in your controllers using dependency injection.
Helpful link: ASP.NET Core Middleware.

AuthenticationManager.RegisteredModules not returning anything

I have inherited a .net framework console app that uses a custom authenticator to connect to a third party API. It works fine and authenticates against the API.
I have migrated this code to .NET Core as I need it part of our main application. The conversion has gone well accept i still couldn't get the authentication to work.
Below is the code that run to register a new authentication method. It's pretty standard.
private static AuthenticationModule registerAuthenticationModule(Uri loginServerUrl)
{
IEnumerator registeredModules = AuthenticationManager.RegisteredModules;
AuthenticationModule authenticationModule;
while (registeredModules.MoveNext())
{
object current = registeredModules.Current;
if (current is AuthenticationModule)
{
authenticationModule = (AuthenticationModule)current;
if (authenticationModule.LoginServerUrl.Equals(loginServerUrl))
{
return authenticationModule;
}
}
}
authenticationModule = new AuthenticationModule(loginServerUrl);
AuthenticationManager.Register(authenticationModule);
displayRegisteredModules();
return authenticationModule;
}
In the .net framework version, AuthenticationManager.RegisteredModules returns 5 standard authentication methods e.g. digest, basic. When i run this within .NET Core it returns none. In fact the list that should store the modules also doesn't exist.
When i then add the new authentication module using AuthenticationManager.Register nothing happens. There is no additional authentication module on the list (which still doesn't exist).
Here is the .NET Framework list showing 5 standard methods plus the custom one at the bottom.
Here is the .NET Core list.
There is very little documentation on the web around this and this is not my area of expertise. Can anyone please give some suggestions as to why this might not be working in .net core. I suspect if i can get this populated it will fix my issues.
Hope the below link would help you to sort the issue with.net core conversion.
What Is The Alternate Of AuthenticationManager In .Net Core
Cheers

Accessing HTTP Headers in ASP.Net Core Business Logic

I am using ASP.Net core and I have a requirement to access a specific HTTP Header in a business logic class (not a controller or action).
To provide a full picture of the configuration here, I have a custom ASP.Net Core Middleware which based on some logic will add a value into a custom HTTP Header, it is the value from this header that I need to access in the business logic class.
Currently the way that I achieve this is to inject an HttpContextAccessor, using the following DI registration.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
In the class which requires access to the HTTP Headers I then request an IHttpContextAccessor using constructor injection and use this to access the relevant HTTP Header.
Doing the above works fine and gives me the results that I require, looking around various articles on the Internet however the general consensus appears to be to avoid using HttpContext.Current in ASP.Net Core.
If the above is the case, is there a better way for my business logic class to access the value that my custom middleware is inserting into a custom HTTP Header?
I should be clear, whilst at present the middleware is storing the required value in a HTTP Header for use by the business logic class, I am open to other methods of the middleware making the required value available to the business logic class if there is a better approach.
Any questions or clarifications, please let me know.
There is no HttpContext.Current in ASP.Net Core, so it's easy to avoid using it. You would have to implement your own extension method if you wanted it, but the general feeling in the .Net Core community is that it's much better to use IHttpContextAccessor.
In earlier versions of .Net Core an implementation of IHttpContextAccessor was auto registered in the DI container. In more current version you have to register it yourself with the line of code you mentioned:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Injecting IHttpContext into your method that needs access to the headers is a workable approach. Or if you like you could use a helper method that places a copy of the headers in a simpler structure and then pass that object in to your class since it doesn't really need access to the full HttpContext.

How to access ASP Core HttpContext in ASP 4.5 class library project?

I have ASP 4.5 website with a dependency on the business logic project, which is a class library built using .Net v4.5. Recently to expand the development, I have planned to introduce additional website project which is ASP Core. For the same, I have added the dependency of the business logic project. The business logic currently evaluates the request, cookies and session related stuff through HttpContext.Current instance. Which isn't working when I am accessing the business logic through ASP Core website.
Access HttpContext.Current
I have gone through the above question, and can know that why HttpContext.Current appears as null when I access it through ASP Core. And the answer to it suggests to populate the reference type IHttpContextAccessor through dependency injection. Now, the problem is, this interface belongs to the library Microsoft.AspNet.Http, and I don't see a way to add this to my business logic project.
Someone please help me out to access HttpContext into my business logic project.
I had this exact same need. The way I solved it was to create my own interfaces that live in my class library and I use those to get access to the current HttpContext regardless of whether the library is running under a 4.5 http context or a MVC Core http context.
To explain further, both the ASP 4.5 framework and the ASP Core Framework have an HttpContext object with associated Request and Response objects but they are defined in different namespaces and neither framework knows about the other framework's namespace. So What I decided is that I needed my library code to have access to an IHttpContext that was defined in one of my namespaces. And that IHttpContext would use an IHttpRequest and IHttpResponse that were also defined in my library's namespace. And finally, that IHttpRequest uses ISession, IHeaders and ICookies that are defined in my namespace.
With these interfaces defined, in my ASP 4.5 website I can now at the web layer create an HttpContext class based on my IHttpContext and have that class basically wrap the ASP 4.5 HttpContext object. My HttpContext object could then be passed into my library for use.
And in my MVC Core website I can now at the web layer create an HttpContext class based on my IHttpContext and have that class basically wrap the MVC Core HttpContext object. My HttpContext object could then be passed into my library for use just like it was when I was running under the ASP 4.5 environment.
So in the end, my library doesn't know which HttpContext object (4.5 or Core) it is actually accessing under the hood because it just knows that the object is has access to confirms to the IHttpInterface defined in it's library.
One final note, to help navigate name conflicts, I actually named my interfaces this way:
IAppHttpContext
IAppHttpRequest
IAppHttpResponse
IAppHttpSession
IAppHttpRequestHeaders
IAppHttpRequestCookies
Note that not all the functionality that is available in HttpContext 4.5 is available in MVC Core. The two are very similar but there are a few differences. The biggest difference is that MVC Core Session can only store byte arrays or strings whereas 4.5 session can store objects. So my IAppSession only supports storing byte arrays and strings and I have to make sure all my library's session needs work with that (all the objects that I need to store in session need to be serializable).
As you can imagine, implementing this is a bit of work, but in the end you will have a library that can access HttpContext and not care if it's running under a 4.5 HttpContext or a MVC Core HttpContext. Kinda neat.
Good luck.
i too had this same problem. I solved it by adding following dependency in my project.json file to add the http packages to class library
"Microsoft.AspNetCore.Http.Abstractions": "1.1.0"
then i used it like below
public class sampleclass
{
private readonly IHttpContextAccessor context;
public ISession GetSession()
{
return context.HttpContext.Session;
}
}
Thank you. Happy Coding :-)
Reference : http://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/

How to register EF DbContext with NetTcpBinding WCF using DI (Castle Windsor WCFFacility)?

I'm using EF6 CodeFirst and WCF 4.5 with NetTcpBinding and BasicHttpBinding. Also I'm using Castle.Windsor for DI.
I have the following architecture:
MySolution.Core (class library)
- Domain
-- (...domain classes...)
- Data
-- IRepository.cs
MySolution.BusinessLogic (class library)
- (...business logic classes...)
MySolution.Data (class library using EF6)
- Models
-- Mapping
-- MyContext.cs (MyContext : DbContext, IDbContext)
- EFRepository.cs (EFRepository : IRepository, where in constructor is injected IDbContext)
- IDbContext.cs
MySolution.Services (WCF Project hosted in IIS with http and net.tcp)
- AppCode
-- Initialization.cs (instead global.asax, to be used with netTcpBinding)
- Installers
-- BusinessLogicInstaller.cs
-- RepositoriesInstaller.cs
-- ServicesInstaller.cs
In AppCode/Initialization.cs I have:
container = new WindsorContainer();
container.AddFacility<WcfFacility>();
container.Install(
new ServicesInstaller(),
new BusinessLogicInstaller(),
new RepositoriesInstaller());
And, inside Installers/RepositoriesInstaller.cs:
public void Install(IWindsorContainer container, IConfigurationStore store)
{
// registration for EF context
container.Register(Classes.FromAssemblyNamed("MySolution.Data")
.InNamespace("MySolution.Data.Models")
.WithService.AllInterfaces()
.LifestylePerWcfOperation());
// registration for EF repository classes
container.Register(Classes.FromAssemblyNamed("MySolution.Data")
.InNamespace("MySolution.Data")
.WithService.AllInterfaces()
.LifestyleTransient());
}
ServicesInstaller and BusinessLogicInstaller register classes with LifestyleTransient.
Obs: The WCF must offer RESTful binding in the future.
My questions are:
If I use netTcpBinding, I cannot use LifestylePerWebRequest for DbContext, right?
It's safe and correct to use LifestylePerWcfOperation for the DbContext? If yes, is OK to use with BasicHttpBinding also? I don't find information explaining in detail the PerWcfOperation.
Is my architecture OK? Maybe I misunderstand some important concept with IoC/DI?
Thanks!
Correct. In WCF, LifestylePerWebRequest only works for HTTP bindings where you have AspNetCompatibility enabled.
LifestylePerWcfOperation can be used with any WCF bindings.
Architecture looks pretty complex but whether it's OK or not depends on the scale and complexity of your application. Really impossible to answer that question sensibly without a ton more information. This sort of architecture is very decoupled and my first questions is whether it's over-engineered for the problem at hand and whether you're also at risk of having anemic domain model.