Custom ClaimsPrincipal in Asp.Net 5 (Mvc 6) - asp.net-core

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

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 difference between AddAuthentication and AddAuthenticationCore?

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.

MVC4, UnitOfWork + DI, and SimpleAuthentication .. how to decouple?

I'm currently working on an MVC4 project, i make use if Ninject to inject a UnitOfWork into my controllers, and I'm using UnitOfWork + Generic Repository pattern.
I don't like VS2012 MVC4 template because it directly uses database access (db initialization, for example).
My project divides in:
a UI project (the mvc4 application), with Forms Authentication
a Domain project (the db entities, the repositories, the UnitOfWork interface plus two UnifOfWork implementations, one with MOQ and one with EF; they are injected into UI controllers via Ninject).
I looked at this example:
http://kevin-junghans.blogspot.it/2013/03/decoupling-simplemembership-from-your.html
related to this question
SimpleMembership - anyone made it n-tier friendly?
And now I have some question:
How can i inject my UoW here? WebSecurity class is static, there is no contructor, it directly instantiate the UoW to perform activities on db ...
I always have to initialize WebMatrix to directly access DB? This piece of code:
public static void Register()
{
Database.SetInitializer<SecurityContext>(new InitSecurityDb());
SecurityContext context = new SecurityContext();
context.Database.Initialize(true);
if (!WebMatrix.WebData.WebSecurity.Initialized)
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
}
breaks my decoupling with the Domain .. how can i make WebSecurity using my UnitOfWork for example? what is the best practice?
How can i store additional data (for example, EmailAddress and so on) and retrieve it, without performing a Database query everytime i have to access the User profile? Something like the old CustomPrincipal ... Custom principal in ASP.NET MVC
Thank you!
You have a lot of questions here Marco. Let me take a stab at them.
How to inject a UOW
Static classes and dependency injection do not mix well, as pointed out in this QA. When I first went through this exercise of decoupling SimpleMembership the concentration was just on decoupling from the domain, as discussed in the article you referenced. It was just a first step and it can be improved on, including making it easier for dependency injection. I debated whether to make WebSecurity static or not and went with static because that is how the original SimpleMembership is implemented, making it a more seamless transition for user of the SimpleSecurity. SimpleSecurity is an open source project and contributions are welcome. Making it non-static would not be difficult and probably makes sense in the long run. Once it is made non-static we could use a Factory pattern to create the UnitOfWork and inject the appropriate Factory.
Why do I have to Register WebSecurity?
SimpleSecurity is just a wrapper around the WebMatrix WebSecurity classes, which require initialization. The Register method just makes sure that WebMatrix is initialized and initializes our database. I disagree that having this method call in the Globa.asax couples it with the Domain in any way. Having it work with your UnitOfWork should have nothing to do with the Application Domain, or with having to call a Register method at application start-up.
How can I store additional data (ex: email) and retrieve it, without performing a database query every time?
This is actually accomplished quite easy in .NET 4.5 by using ClaimsPrincipal. All principals in .NET 4.5 inherit from ClaimsPrincipal, which allows you to store information in the principal as claims. Claims are basically key value pairs that let you store any type of data on the user. For example in ASP.NET the roles for a user are stored as claims. To add your own claims you need to do something called claims transformation. Then to retrieve the information you can create a custom claims principal. Adding this to SimpleSecurity would be a nice feature.

ASP.NET, MVC 3, EF 4.1: Filtering data based on ASP.NET Authentication login

If you have a decent layered ASP.NET MVC 3 web application with a data service class pumping out view models pulled from a repository, sending JSON to an Ajax client,
[taking a breath]
what's a good way to add data filtering based on ASP.NET logins and roles without really messing up our data service class with these concerns?
We have a repository that kicks out Entity Framework 4.1 POCOs which accepts Lambda Expressions for where clauses (or specification objects.)
The data service class creates query objects (like IQueryable) then returns them with .ToList() in the return statement.
I'm thinking maybe a specification that handles security roles passed to the data service class, or somehow essentially injecting a Lambda Expression in just the right place in the data service class?
I am sure there is a fairly standardized pattern to implement something like this. Links to examples or books on the subject would be most appreciated.
If you've got a single-tiered application (as in, your web layer and service/data layer all run in the same process) then it's common to use a custom principal to achieve what you want.
You can use a custom principal to store extra data about a user (have a watch of this: http://www.asp.net/security/videos/use-custom-principal-objects), but the trick is to set this custom principal into the current thread's principal also, by doing Thread.CurrentPrincipal = myPrincipal
This effectively means that you can get access to your user/role information from deep into your service layer without creating extra parameters on your methods (which is bad design). You can do this by querying Thread.CurrentPrincipal and cast it to your own implementation.
If your service/data layer exists in a different process (perhaps you're using web services) then you can still pass your user information separately from your method calls, by passing custom data headers along with the service request and leave this kind of data out of your method calls.
Edit: to relate back to your querying of data, obviously any queries you write which are influence by some aspect of the currently logged-in user or their role can be picked up by looking at the data in your custom principal, but without passing special data through your method calls.
Hopefully this at least points you in the right direction.
It is not clear from your question if you are using DI, as you mentioned you have your layers split up properly I am presuming so, then again this should be possible without DI I think...
Create an interface called IUserSession or something similar, Implement that inside your asp.net mvc application, the interface can contain something like GetUser(); from this info I am sure you can filter data inside your middle tier, otherwise you can simply use this IUserSession inside your web application and do the filtering inside that tier...
See: https://gist.github.com/1042173

Why use ASP.NET MVC 2 for REST services? Why not WCF?

So I see that MVC 2 now supports [HttpPut] and [HttpDelete] as well as [HttpGet] and [HttpPost], making it possible to do a full RESTful Web service using it.
I've been using the REST toolkit for WCF for a while and find it fairly powerful, but I'd be interested to find out what (if any) advantages there are using the MVC 2 approach.
Links, war stories, or even pure hear-say are welcome.
I'm pretty sure ASP.NET MVC has supported all the HTTP verbs since the beginning. At least the HttpVerb Enumeration has had them from the beginning. The only thing that's new in V2 is that they are attributes.
// V1
[AcceptVerbs( HttpVerbs.Delete )]
// V2
[HttpDelete]
Six of one, half a dozen of the other. As to whether you want to expose functionality through WCF or ASP.NET MVC, it would come down to how you think of your application.
If you think of it as a thick client app that just happens to be written in JavaScript and calls out to restful services for data (then formats it client side) then WCF would feel like a more correct solution (even though you could do it using either).
However if you think of your application as a server app that returns content in some form or another for consumption, then using a RESTful API for your actions would make more sense. Your actions would return fully formatted content that would be displayed in the browser without a need for further processing. You could return formatted content (HTML or otherwise) from a web service, but that would somehow feel wrong.
At least that kind of distinction makes sense in my head =). You may also be interested in Phil Haack's post on How a Method Becomes an Action.
There's now another option, Web API. ScottGu has a brief introduction in his blog and there's an interesting blog post discussing creating APIs using the Web API vs controllers here.
You should check an interesting Blog shouldersofgiants Who made a series of post on Creating RESTful WebService with ASP.Net MVC.
from Part 1 to Part 21 you might find some iteresting information. And he's not even done yet... good reading.
I can't talk for the MVC toolkit, but personally I find WCF a pain to work with. It does have uses, but it's quite a heavy framework and can be quite awkward to use at times.
If you want to go down the REST route, OpenRasta is the best .Net solution currently around. Especially in terms of compliance.
You can also forge the ASP MVC framework to be RESTful, but that requires a fair bit of work (compared to OpenRasta which works out of the box).
We use ASP.Net MVC 1.0 to create JSON services.
There are a couple of reasons for this:
We were using ASP.Net MVC for the pages, so using it for the services as well reduces the number of technologies in the project.
We found it very easy to use for returning an ActionResult with JSON formatted data
public ActionResult GetData(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id", "Searchvalue must be provided.");
}
// Where Provider.GetData returns IEnumerable<Data>
return Json(Provider.GetData(id));
}