ASP.Net Idenity - Override FindByName to include extra search criteria - c#

We have a setup where clients run stand-alone version of our system, but they all link to the same Identity Database with Entity Framework.
A user can be registered as a user on many versions of the application, thereby having multiple accounts with the same username, but the applicationId (stored in the web.config) is unique.
What I would like to do is use the UserManager.FindByName function, but have it automatically add the "&& applicationId = X" to the request sent to the context.

Well you can inherit from the UserManager class, but you have to rewrite the original code (.NET now is open source you can find the original code) and add your logic to it. However, this may be a lengthy action.
What i suggest is if you are using Entity Framework search for the user id by name and application id, then pass the id for the FindById method.

If follow down the implementation, you'll eventually find this method:
public virtual Task<TUser> FindByIdAsync(TKey userId)
{
this.ThrowIfDisposed();
return this.GetUserAggregateAsync((Expression<Func<TUser, bool>>) (u => u.Id.Equals(userId)));
}
In order to override this properly, it would have to be inside the UserStore class, since there are loads of internal methods (otherwise you'd have to rewrite every single internal method in the class), and add a new Type Parameter that would accept your ApplicationId, since UserStore is a generic class. Then you would be able to write another FindByIdAsync method, because it's a virtual method and it can't be overridden. You would also have to rewrite the GetUserAggregateAsync internal method, because it isn't prepared to handle your new Type Parameter.
Now, there are probably a few more hiccups that would show up, but you can, ultimately, rewrite this method to suit you, but I would advise against it because it's A LOT of work to achieve something that might be possible in another way.
Docs: http://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNet/Identity/EntityFramework/UserStore-TUser-TRole-TContext-TKey/index.html
Code: https://github.com/aspnet/identity/blob/master/src/Microsoft.AspNet.Identity.EntityFramework/UserStore.cs

Related

Alternative for initializing properties in the constructor in (Dynamics) CRM

I'm currently working one a custom CRM-style solution (EF/Winforms/OData WebApi) and I wonder how to implement a quite simple requirement:
Let's say there is a simple Project entity. It is possible to assign Tasks to it. There is a DefaultTaskResponsible defined in the Project. Whenever a Task is created, the Project's DefaultTaskResponsible is used as the Task.Responsible. But it is possible change the Task.Responsible and even set it to null.
So, in a 'normal' programming world, I would use a Task constructor accepting the Project and set the Responsible there:
public class Task {
public Task(Project p) {
this.Responsible = p.DefaultTaskResponsible;
...
}
}
But how should I implement something like this in a CRM-World with Lookup views? In Dynamics CRM (or in my custom solution), there is a Task view with a Project Lookup field. It does not make sense to use a custom Task constructor.
Maybe it is possible to use Business Rules in Dynamics CRM and update the Responsible whenever the Project changes (not sure)?! But how should I deal with the WebApi/OData Client?
If I receive a Post to the Task endpoint without a Responsible I would like to use the DefaultTaskResponsible, e.g.
POST [Organization URI]/api/data/tasks
{
"project#odata.bind":"[Organization URI]/api/data/projects(xxx-1)"
}.
No Responsible was send (maybe because it is an older client), so use the default one. But if a Responsible is set, the passed value should be used instead, e.g.
POST [Organization URI]/api/data/tasks
{
"project#odata.bind":"[Organization URI]/api/data/projects(xxx-1)",
"responsible#odata.bind": null
}.
In my TaskController I only see the Task model with the Responsible being null, but I don't know if it is null because it was set explicitly or because it wasn't send in the request.
Is there something wrong with my ideas/concepts? I think it is quite common to initialize properties based on other objects/properties, isn't it?
This question is probably out of scope for this forum, but it is a subject I am interested in. A few thoughts:
A "Task" is a generic construct which traditionally can be associated with many different types of entities. For example, you might not only have tasks associated with Projects, but also with Customer records and Sales records. To run with your code example it would look like:
public Task(Entity parent) {}
Then you have to decide whether or not your defaulting of the Responsible party is specific to Projects, or generic across all Entities which have Tasks. If the latter, then our concept looks like this:
public Task(ITaskEntity parent)
{
this.Responsible = parent.DefaultResponsible; //A property of ITaskEntity
}
This logic should be enforced at the database "pre operation" level, i.e. when your CRM application receives a request to create a Task, it should make this calculation, then persist the task to the database. This suggests that you should have a database execution pipeline, where actions can be taken before or after database operations occur. A standard simple execution pipeline looks like this:
Validation -> Pre Operation -> Operation (CRUD) -> Post Operation
Unless you are doing this for fun, I recommend abandoning the project and using an existing CRM system.

ASP.NET WebAPI - how to create an abstract layer for multiple services

Alright, so assuming I am making a fancy web store.
I have a payment provider (say, paypal) which requires the user to sign into paypal website, confirm the credentials and then to redirect him into my website.
So basically the code behind that would look like this:
class PaymentManager
{
public string AcceptPayment(Payment payment)
{
//return redirect url
}
public bool ConfirmPayment(string paymentToken)
{
//if token is valid the payment succeded
}
}
So basically the usage of this manager from my controller maps into 2 controller methods (each requiring an individual request).
Now, assuming I have a different payment manager, which requires 3 methods being sequentially executed instead of 2. Something like:
class AnotherPaymentManager
{
public string AcceptPayment(Payment payment)
{
//return validation redirect url
}
public string ValidatePayment(string validationCode)
{
//return redirect url
}
public bool ConfirmPayment(string paymentToken)
{
//if token is valid, confirm payment
}
}
Now this class' usage maps into 3 controller methods (we need the client to execute the Accept method to declare payment, then to execute the Validate method to validate it and after all to execute the Confirm method to make sure the server has accepted it).
The question is: provided these managers have different API usage scenarios to do the same thing (as shown above), is there a way to make an abstract layer between them and the controller? I mean something like:
interface IPaymentManager
{
void MakePayment(); //this controls the payment methods flow
//Something like (Accept -> Confirm) in the former case
//and (Accept -> Validate -> Confirm) in the latter
}
I am doing this in ASP.NET WebAPI 2, but I think it may apply to MVC as well.
If I understand correctly, when a user creates a transaction they are redirected to the payment provider (with a redirect url in the response). Once there they confirm their credentials which returns them to your fancy web store (with a confirmation token provided by the payment provider). If that token is valid then the transaction was successful. Also each of those actions require a separate endpoint in your controller.
If those assumptions are correct, I would say it is not necessary, or even recommended, to create an abstraction here. Also there is response data (validationCode, paymentToken, etc.) from the payment provider which your PaymentManger functions and controller endpoints are dependent on in order to proceed in the process.
In my experience, trying to abstract too early can make more work for you down the road. Without more information (more implementations of payment provider clients) you might make abstractions that are too specific - which can not be used for different PaymentManager types you add later.
However, if you already posses this data (validationCode, etc.), then you could abstract here, but I would still say it is unnecessary, and potentially a waste of time.
If you are determined to abstract here, then you can implement your interface in each of your PaymentManager classes. Having each PaymentManger implement the MakePayment function which would call the respective PaymentManager functions.
Again, I would not recommend abstracting here. It doesn't make sense, and really won't be that helpful in my opinion. Wait until you implement a few more PaymentManager classes. Then you will be able to more accurately see the patterns between the different types of PaymentMangers and abstract those patterns out.
If my understanding of the problem was not correct, let me know where I misunderstood the problem, and I will try to answer it again.
On a side note, I would recommend looking into asynchronous functions and the await operator, if you haven't already and are making calls to an external API.
Hope this helps.

Attribute Useage For Checking Method Permissions

I'm trying to implement a security mechanism to automatically test a particular plugins permissions and method security privileges and I've gotten a bit stuck on how to get this working.
I've writing a custom MEF Metadata attribute that takes a constructor property like:
params PluginPermission[] permission
This contains an array of all the permissions that the plugin is granted.
The PluginPermission class looks like:
PluginPermission.cs
public enum PluginPermission
{
CreateUsers,
DeleteUsers,
ReadPassword,
WritePassword,
AddUsersToGroups,
AddGroups,
DeleteGroups
}
I've also written a RequiredPermissionAttribute that targets individual methods and takes one or more PluginPermission objects to tell the system what permissions are required for an individual method to be execute. These are applied to the interface for the plugins like:
ILicensingManagement.cs
[RequiredPermission(PluginPermission.CreateUsers)]
bool AddUser(string userName);
Obviously if the plugin doesn't have the required permissions for a particular method the method is not executed.
What I'm stuck on is how to actually get the test method in the RequiredPermissionAttribute class to run before the method is executed and how to gracefully exit the execution if the permissions requirements for the method are not met by the plugin.
I looked at the xUnit BeforeAfterTestAttribute but the implementation seemed so specific I stuggled to pull the source code apart to arrive at the solution.
I can't comment on MEF specific things but one thing to keep in mind that custom attributes are nothing more than "tags", they do not do anything unless your code specifically checks for them, for example using reflection.
The BeforeAfterTestAttribute of xUnit probably works, because xUnit uses reflection to execute the methods. When it encounters this attribute it changes its behavious accordingly.
Attributes in the .NET framework namespace work because either the CLR checks for them or the compiler does.
I know this doesn't really answer your question completely but it was a bit too long to put into a comment.
Update: you can access the attributes using the Type if it's a class or the MethodInfo if it's a method, e.g.
MethodInfo mi = /* method info */;
Attribute[] attrs = mi.GetCustomAttributes(typeof(RequiredPermissionAttribute), false);
RequiredPermissionAttribute req = attrs.Cast<RequiredPermissionAttribute>().FirstOrDefault();
if ((req != null) && (/* current user does not have the required permission */)) throw new Exception();
But this is not a real security solution, a developer can easily avoid these checks. I've only briefly glanced at it but PostSharp could maybe help you.

SQL role security + custom ASP.Net base page

I'm workng on a new, green-field ASP.Net application. We're implementing a base page which all pages will be, er, based on. The application will be running under Integrate Windows Auth, so I'll have the user's account details. With these, I'll be going to several databases (in which the user will exist) to find out what roles they are assigned to in each db. I'll be holding the role yay/nay in a bool array, and key into it via an enum.
There will be a session object that will hold a few things, and the roles assigned for that user. I'm thinking of making the session object available as a property of the base page, as the code would be something like this:
public SessionObject MasterSessionObject
{
get
{
if (Session["SessionObject"] == null)
{
// Create session object, assign user name, etc.
// Do something with roles...
Session["SessionObject"] = sessionObject;
}
return (SessionObject)Session["SessionObject"]
}
}
In order to control what happens on the (sub-classed) page, I want to provide a CheckSecurity method - e.g. if the user is not authorised to a certain part of a page, it can be hidden / disabled, or they could be booted back to a "not yours" page. The logical place for it is the base page, but seeing as the base page is already exposing the SessionObject that holds the roles permissions, would it not make more sense to Create a DatabaseSecurity type object and have the check on that?
Dealing with the latter approach, I've used abstract base classes to get me so far: I have a DatabaseRoles abstract class which contains the bool array, and a method to retrieve the roles for the user. The concrete implementation holds an Enum (as previously mentioned) to key into the array (in the base class). The abstract class also has the CheckRole method which takes in an int, to which I'm intending use a cast of the enum...
The SessionObject contains several of these DatabaseRoles implementations, and essentially does away with the need for a CheckSecurity in the base page class, leading to code like this in the actual page:
if (MasterSessionObject.SampleDatabaseRoles.Check((int)SampleDatabaseRolesEnum.RoleView))
{
// Do something
}
But, I'm sure you'll agree, it looks sucky...
If there was a CheckSecurity method on the base page, it would have to take a concrete DatabaseRoles object, but also an enum of which role to check, which would also look sucky. And finally, there would be a requirement at a later date to add more databases and their security settings...
I'll add code tomorrow if required... :-s
I dunno, I'm not that thick, but I do have a hard time sometimes binding all this together...
Thank you,
Mike K.
IF you happen to use ASP.Net / ASP.Net MVC, I would say the best place to do this would be via a custom HTTP Module by handling the AuthenticateRequest method & continuing with the request only if the request has been authenticated. There are tons of excellent articles online for this code.
Also - have a look at the Roles & Memberships of ASP.Net - it is pretty good & generally satisfies most requirements or you are always free to extend it. Again - tons of articles on custom membership providers...
unless I am missing something - HTH.

Suggestions on how to map from Domain (ORM) objects to Data Transfer Objects (DTO)

The current system that I am working on makes use of Castle Activerecord to provide ORM (Object Relational Mapping) between the Domain objects and the database. This is all well and good and at most times actually works well!
The problem comes about with Castle Activerecords support for asynchronous execution, well, more specifically the SessionScope that manages the session that objects belong to. Long story short, bad stuff happens!
We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM).
Does anyone have suggestions on doing this. For the start I am looking for a basic One to One mapping of object. Domain object Person will be mapped to say PersonDTO. I do not want to do this manually since it is a waste.
Obviously reflection comes to mind, but I am hoping with some of the better IT knowledge floating around this site that "cooler" will be suggested.
Oh, I am working in C#, the ORM objects as said before a mapped with Castle ActiveRecord.
Example code:
By #ajmastrean's request I have linked to an example that I have (badly) mocked together. The example has a capture form, capture form controller, domain objects, activerecord repository and an async helper. It is slightly big (3MB) because I included the ActiveRecored dll's needed to get it running. You will need to create a database called ActiveRecordAsync on your local machine or just change the .config file.
Basic details of example:
The Capture Form
The capture form has a reference to the contoller
private CompanyCaptureController MyController { get; set; }
On initialise of the form it calls MyController.Load()
private void InitForm ()
{
MyController = new CompanyCaptureController(this);
MyController.Load();
}
This will return back to a method called LoadComplete()
public void LoadCompleted (Company loadCompany)
{
_context.Post(delegate
{
CurrentItem = loadCompany;
bindingSource.DataSource = CurrentItem;
bindingSource.ResetCurrentItem();
//TOTO: This line will thow the exception since the session scope used to fetch loadCompany is now gone.
grdEmployees.DataSource = loadCompany.Employees;
}, null);
}
}
this is where the "bad stuff" occurs, since we are using the child list of Company that is set as Lazy load.
The Controller
The controller has a Load method that was called from the form, it then calls the Asyc helper to asynchronously call the LoadCompany method and then return to the Capture form's LoadComplete method.
public void Load ()
{
new AsyncListLoad<Company>().BeginLoad(LoadCompany, Form.LoadCompleted);
}
The LoadCompany() method simply makes use of the Repository to find a know company.
public Company LoadCompany()
{
return ActiveRecordRepository<Company>.Find(Setup.company.Identifier);
}
The rest of the example is rather generic, it has two domain classes which inherit from a base class, a setup file to instert some data and the repository to provide the ActiveRecordMediator abilities.
I solved a problem very similar to this where I copied the data out of a lot of older web service contracts into WCF data contracts. I created a number of methods that had signatures like this:
public static T ChangeType<S, T>(this S source) where T : class, new()
The first time this method (or any of the other overloads) executes for two types, it looks at the properties of each type, and decides which ones exist in both based on name and type. It takes this 'member intersection' and uses the DynamicMethod class to emil the IL to copy the source type to the target type, then it caches the resulting delegate in a threadsafe static dictionary.
Once the delegate is created, it's obscenely fast and I have provided other overloads to pass in a delegate to copy over properties that don't match the intersection criteria:
public static T ChangeType<S, T>(this S source, Action<S, T> additionalOperations) where T : class, new()
... so you could do this for your Person to PersonDTO example:
Person p = new Person( /* set whatever */);
PersonDTO = p.ChangeType<Person, PersonDTO>();
And any properties on both Person and PersonDTO (again, that have the same name and type) would be copied by a runtime emitted method and any subsequent calls would not have to be emitted, but would reuse the same emitted code for those types in that order (i.e. copying PersonDTO to Person would also incur a hit to emit the code).
It's too much code to post, but if you are interested I will make the effort to upload a sample to SkyDrive and post the link here.
Richard
use ValueInjecter, with it you can map anything to anything e.g.
object <-> object
object <-> Form/WebForm
DataReader -> object
and it has cool features like: flattening and unflattening
the download contains lots of samples
You should automapper that I've blogged about here:
http://januszstabik.blogspot.com/2010/04/automatically-map-your-heavyweight-orm.html#links
As long as the properties are named the same on both your objects automapper will handle it.
My apologies for not really putting the details in here, but a basic OO approach would be to make the DTO a member of the ActiveRecord class and have the ActiveRecord delegate the accessors and mutators to the DTO. You could use code generation or refactoring tools to build the DTO classes pretty quickly from the AcitveRecord classes.
Actually I got totally confussed now.
Because you are saying: "We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM)."
Domain objects know and care about DB? Isn't that the whole point of domain objects to contain business logic ONLY and be totally unaware of DB and ORM?....You HAVE to have these objects? You just need to FIX them if they contain all that stuff...that's why I am a bit confused how DTO's come into picture
Could you provide more details on what problems you're facing with lazy loading?

Categories