What is the difference between AddAuthentication and AddAuthenticationCore? - authentication

Looking at the code for AuthenticationServiceCollectionExtensions.AddAuthentication() vs AuthenticationCoreServiceCollectionExtensions.AddAuthenticationCore(), it looks like AddAuthentication implicitly calls AddAuthenticationCore, adds some other goodies, and then returns a new instance of AuthenticationBuilder instead of just returning IServiceCollection.
Am I understanding the code correctly? If so, are there generally any reasons to call AddAuthenticationCore instead of AddAuthentication outside of writing your own extension?

It seems to be a typical pattern in ASP.NET Core: the Add[xxx]Core methods add the bare minimum to enable a feature, but without any bells and whistles. It's also probably used to make unit testing the core features easier.
You can make a parallel with the AddMvc vs AddMvcCore methods. There's a question that asks Should I use AddMvc or AddMvcCore for ASP.NET Core MVC development?, and the gist is that it allows for fine-grained control on what middleware you want to use.
To answer your question: for a typical user, there's probably no reason to use AddAuthenticationCore.

Actually there is a reason. Currently AddAuthentication() also adds data protection services, which you may not need - for example if you are writing your own Authentication Scheme. So instead you can do this:
services.AddAuthenticationCore(o => {
o.DefaultScheme = "My Custom Scheme";
});
services.AddWebEncoders();
services.AddSingleton<ISystemClock, SystemClock>();
var authBuilder = new AuthenticationBuilder(services);
however I fully expect this to break in future versions of asp.net core as it's undocumented and a bit of a hack.

Related

Should I use IEmailSender?

I'm using AspNetCore.Identity at my project, so I write a EmailSender class that implements this interface.
Everything is working fine.
But this description about IEmailSender took my attention:
Microsoft.AspNetCore.Identity.UI.Services.IEmailSender
This API supports the ASP.NET Core Identity default UI infraestructure and is not intended to be used directly from your code. This API may change or be removed in future releases
If it isn't intended to be used directly in my code, what should I use?
My application also send emails in other parts, not only for Identity.
I don't think you need to use IEmailSender. In fact, based on my experience, to some degrees I think you shouldn't use it:
In .NET 5.0, IEmailSender is in the package ASP.NET Core Identity.UI, with the default implementation injected in DI that doesn't do anything. It's perfectly fine if you want to use the default UI provided by the framework. But if you don't like to use those default pages and just want to use the core of the Identity framework, including the whole package just to get IEmailSender interface seems overkill to me. Not to mention there is an annoying bug when using Identity UI at this moment.
It doesn't add any value. I would have been persuaded if the framework could automatically scan my concrete implementation and use that instead to send out emails. But that's not the case. You would have to inject your email sender through DI by services.AddSingleton<>() yourself and use it via constructor injection where you want to send emails.
IEmailSender.SendEmailAsync(string email, string subject, string htmlMessage) method is pretty basic. Most of the time you even would have to create your own razor library to generate the HTML message yourself. In my case (using SendGrid v9.22 with dynamic template), I would need to not only pass the HTML message, but also the template data (for setting the placeholder in my SendGrid template via msg.SetTemplateData()). The basic SendEmailAsync() just doesn't have extra parameters for me to send additional data when sending the email.
Conclusion:
If you see yourself that you won't switch to email provider for a project, you might as well just create a concrete email sender that fits you well, and inject that into DI directly.
If you see there might be a time when your project will switch email provider, having a basic and simple interface, like IEmailSender, makes sense.
You definitely should, as the IEmailSender is the best available option offered by the framework to send email messages, especially if you have to deal with ASP.NET Identity stuff (account confirmation, password recovery and so on).
However, in order to use it properly, you should implement it using one of the many third-party services (and their corresponding .NET NuGet packages), as suggested in this official post.
If you need further instruction to setup these email sender provider, you can take a look at these implementation guides that I wrote on my blog (DISCLAIMER: I'm not affiliated with any of them):
.NET Core General Purpose SMTP implementation using MailKit
.NET Core IEmailSender implementation using Twilio SendGrid API
.NET Core IEmailSender implementation using SendInBlue API
The fact that the API could get removed in the future shouldn't bother you at all, since all of these third-party packages have their own API: you'll be able to use them even without the IEmailSender interface (as a matter of fact, you already can).

What is the point of IStartupFilter in asp.net core?

IStartupFilter is the basis of a mechanism for libraries to add middleware to the app. According to the Docs "IStartupFilter is useful to ensure that a middleware runs before or after middleware added by libraries at the start or end of the app's request processing pipeline".
Does the mechanism allow you to manipulate the pipeline in any way that can't be done from Startup.Configure()?
If the point is modularity then you just seem to be trading coupling through Startup.Configure() for coupling via the IServicesCollection (a call to DI is required). In the simple case (as per the example) a call to services.AddTransient<IStartupFilter, ...>() can be removed from ConfigureServices() and app.AddMiddleware<MyMiddleware>() can be added to achieve the same functionality with less complexity and magic.
Is the main point of the mechanism to allow the library to apply conditions as to what middleware should be included? If so, it seems to lack asp.net core's customary economy and clarity of design.
In the simple case (as per the example) a call to services.AddTransient<IStartupFilter, ...>() can be removed from ConfigureServices() and app.AddMiddleware() can be added to achieve the same functionality with less complexity and magic.
That's not true.
There is a big difference between using IStartupFilter and using a middleware. A middleware is part of the request pipeline, which means it gets executed on every request. On the other hand, IStartupFilter gets executed just once when the application starts (not on every request).
To answer my own question, I think that the main use case is to enable the framework to encorporate assemblies that were not known at build time. The docs cover this in the aspnetcore/Fundamentals/Host nhance an app from an external assembly in ASP.NET Core with IHostingStartup. (Although the documentation makes no mention of IStartupFilter the associated StartupDiagnostics sample project does.
IStartupFilter is usually used when you do not want any intervention from app’s author i.e. you don’t want that app.Usexxxx() to get called but a different component should configure that middleware. Now, consider a scenario where you want to execute certain code even if the request pipeline is not executed.
Lets take a URI which does not exist and returns 404 error, in that case request processing pipeline won’t be executed but startup filter will be.
A simple answer is no, it doesn't add any new functionality.
The point behind the IStartupFilter is to run some stuff in the pre-defined order independently on how yours Startup.Configure method changes. It simply creates a sequence of methods they do actions on IApplicationBuilder (WebHostBuilder) to build the middleware pipeline. You can define action that will perform before or after the Startup.Configure method is called.
Your IStartupFilter implementation will look similarly to this:
public class ExampleStartupFilter : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return builder =>
{
// This will run before the Startup.Configure
builder.UseMiddleware<PreStartupConfigureRegisteredMiddleware>();
// This is Startup.Configure (or the next IStartupFilter.Configure in the sequence)
next(builder);
// This will run after Startup.Configure
builder.UseMiddleware<AfterStartupConfigureRegisteredMiddleware>();
};
}
}
Arguably, as you have to register your IStartupFilter in the Startup.ConfigureServices method and the order the filters are registered is the order they will be performed, there is not much difference compare to the order of direct registrations of UseMiddleware in Startup.Configure.
The only benefit I can see is that you can register something that has absolutely run the first or the last in the pipeline, no matter what other middlewares you use. Then you don't have to worry about changes in the Configure method. It should, however, be used very scarcely.
Very good blog post explaining how the IStartupFilter works has been written by Andrew Lock, check it out here:
https://andrewlock.net/exploring-istartupfilter-in-asp-net-core/
One thing Andrew points out is that you can register filter to run it prior to the AutoRequestServicesStartupFilter registered automatically by the WebHostBuilder. Not that I would be aware of an example where this would have a practical use.

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.

Custom ClaimsPrincipal in Asp.Net 5 (Mvc 6)

How can I override the default Context.User of type System.Security.Claims.ClaimsPrincipal in Asp.Net 5 (MVC-6)?
I would like to use my customized User-type, so that it's accessible in Controllers (HttpContext.User), as well as in the Razor views (#User.)
Any help is much appreciated. Thanks!:)
The basic answer is don't - it's generally a bad idea to try to implement your own security code; there's lots of options out there that will save you a lot of time up front, and save you a lot of headaches on the back side, too.
The other answer is that you can't - it's built in to the new framework from the beginning.
This is what a User POCO model is for. The Identity framework has operated this way (I think since the beginning), and it mirrors OAuth and most other authentication/authorization systems. It's an incredibly flexible and efficient model.
Instead what I would recommend doing is build your own ClaimTypes and use those in addition to the ones built in to the framework. Depending on how you're authenticating the user, you should be able to add them when you would create the IPrincipal, anyway.
Short answer - assign custom .User to HttpContext in middleware.
Long answer: Where to set custom ClaimsPrincipal for all HttpRequests

ServiceStack and NHibernate Unit Of Work Pattern

Long story as brief as possible...
I have an existing application that I'm trying to get ServiceStack into to create our new API. This app is currently an MVC3 app and uses the UnitOfWork pattern using Attribute Injection on MVC routes to create/finalize a transaction where the attribute is applied.
Trying to accomplish something similar using ServiceStack
This gist
shows the relevant ServiceStack configuration settings. What I am curious about is the global request/response filters -- these will create a new unit of work for each request and close it before sending the response to the client (there is a check in there so if an error occurs writing to the db, we return an appropriate response to the client, and not a false "success" message)
My questions are:
Is this a good idea or not, or is there a better way to do
this with ServiceStack.
In the MVC site we only create a new unit
of work on an action that will add/update/delete data - should we do
something similar here or is it fine to create a transaction only to retrieve data?
As mentioned in ServiceStack's IOC wiki the Funq IOC registers dependencies as a singleton by default. So to register it with RequestScope you need to specify it as done here:
container.RegisterAutoWiredAs<NHibernateUnitOfWork, IUnitOfWork()
.ReusedWithin(ReuseScope.Request);
Although this is not likely what you want as it registers as a singleton, i.e. the same instance returned for every request:
container.Register<ISession>((c) => {
var uow = (INHibernateUnitOfWork) c.Resolve<IUnitOfWork>();
return uow.Session;
});
You probably want to make this:
.ReusedWithin(ReuseScope.Request); //per request
.ReusedWithin(ReuseScope.None); //Executed each time its injected
Using a RequestScope also works for Global Request/Response filters which will get the same instance as used in the Service.
1) Whether you are using ServiceStack, MVC, WCF, Nancy, or any other web framework, the most common method to use is the session-per-request pattern. In web terms, this means creating a new unit of work in the beginning of the request and disposing of the unit of work at the end of the request. Almost all web frameworks have hooks for these events.
Resources:
https://stackoverflow.com/a/13206256/670028
https://stackoverflow.com/search?q=servicestack+session+per+request
2) You should always interact with NHibernate within a transaction.
Please see any of the following for an explanation of why:
http://ayende.com/blog/3775/nh-prof-alerts-use-of-implicit-transactions-is-discouraged
http://www.hibernatingrhinos.com/products/nhprof/learn/alert/DoNotUseImplicitTransactions
Note that when switching to using transactions with reads, be sure to make yourself aware of NULL behavior: http://www.zvolkov.com/clog/2009/07/09/why-nhibernate-updates-db-on-commit-of-read-only-transaction/#comments