Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstracting asp.net mvc identity from UI layer

I'm building a new MVC application. Normally I always have a project structure that looks like this:

  • DAL layer (entities and repositories
  • Service layer (business oriented service calls that coordinate between the api/Frontend and the DAL)
  • Frontend, this can be web API or MVC application.

My problem is that I always end up with a messy implementation for user management. I used the Membership providers and thus made that part not as nice as it should. Now I saw the new Identity implementation and I really liked it. I did some searches about hot to abstract it to the backend, but with no result.

I found this post about structuring the project but it gave no real answer: Decoupling ASP.NET MVC 5 Identity to allow implementing a layered application

I was hoping someone could provide me with some hints or a technical document how abstract all login and authentication to the backend layer.

like image 987
Patrick Avatar asked Jan 23 '14 11:01

Patrick


2 Answers

You could create a pretty basic interface in your business layer. It would look something like this:

public interface IAuthenticationService
{
    bool VerifyPassword(User user, string password);

    bool SignIn(User user);

    void SignOut();
}

You can implement this interface using ASP.NET Identity in either the business layer, the UI layer or a seperate infrastructure layer.

This interface could be implemented by different technologies which can be registered at runtime by an IoC container and you could just use the interface in your AccountController for example. Since authentication frameworks tend to change often (every year or so), this allows you to switch more easily.

like image 135
Henk Mollema Avatar answered Oct 28 '22 14:10

Henk Mollema


Technically, it's already abstracted. The UserManager class, central to ASP.NET Identity, is a wrapper around your database context. Now, if you're talking about abstracting it further, so there's no reference to ASP.NET Identity at all in your code, I'd say that's unnecessary, but still possible. You can simply move all that code into your service layer and then make calls to your service to hit the appropriate methods on UserManager. You'll still need to pass your context around, though, so that you don't end up creating multiple instances of it, which will bite you, for sure.

like image 4
Chris Pratt Avatar answered Oct 28 '22 14:10

Chris Pratt