hyperN
hyperN

Reputation: 2754

Asp.net web API 2 authentication with asp.net Identity

I have Solution consisting of 3 projects, first is Data Access Layer (where models and Database Context are defined), and other two are Asp.net MVC 5 and Asp.net Web Api 2 projects.

For authentication and authorization I'm using Asp.net Identity which I've set up like this (in my DAL project):

public class DatabaseContext : IdentityDbContext<User>
{
    public DatabaseContext()
        : base("DefaultConnection")
    {
        Configuration.LazyLoadingEnabled = true;
    }

    public DbSet<IdentityUser> IdentityUsers { get; set; }

    /*
        Other DbSets ...
    */
}

My User class extends IdentityUser.

In my ASP.net project I've changed a bit Account controller so it works with my Database Context, here are relevant parts which I changed:

[Authorize]
public class AccountController : Controller
{
    public AccountController()
        : this(new UserManager<User>(new UserStore<User>(new DatabaseContext())))
    {
    }

    public AccountController(UserManager<User> userManager)
    {
        UserManager = userManager;
    }

    public UserManager<User> UserManager { get; private set; }
}

And this part works fine. So my question is, what changes I have to do in order my Web API project works with my entity User and my Database Context, so in order to consume API user must be logged in ? (and of-course user has option to register via API).

I.E. I want to enable authorization and authentication for web api 2 by using my Database Context and class User which extends Identity User class.

UPDATE

What I've tried to do is this: I've replaced all IdentityUser classes in my web api 2 project with my class User, but on line (when I try to log in):

User user =  await userManager.FindAsync(context.UserName, context.Password);

I get error:

System.Data.SqlClient.SqlException: Invalid object name 'dbo.AspNetUsers'.

This approach worked for my asp.net MVC project.

Upvotes: 1

Views: 3935

Answers (1)

hyperN
hyperN

Reputation: 2754

In short what I did was:

In my DatabaseContext class I've added these lines:

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>()
            .ToTable("AspNetUsers");
        modelBuilder.Entity<User>()
            .ToTable("AspNetUsers");
    }

In asp.net web api project I've changed all classes IdentityUser to User, and that's it

Upvotes: 1

Related Questions