0

I was seeking on the internet a bit, but couldn't find exactly what I meant...

Could you please elaborate what exactly I'm doing wrong here and how can I actually accomplish what I need? Issue explained in code comment just below multiple strings.

um.FindByName(username) - of course gives me an error "The entity type ApplicationUser is not part of the model for the current context"

public class MyNewAuthenticationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {


        if (actionContext.Request.Headers.Authorization == null)
        {
            base.OnAuthorization(actionContext);
        }
        else
        {
            string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
            string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
            string[] usernamePasswordArray = decodedToken.Split(':');
            string username = usernamePasswordArray[0];
            string password = usernamePasswordArray[1];


            // Here is the issue. I need to check whether the user is in admin role....
            var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new WeatherAppDbEntities()));
            var user = um.FindByName(username);

            var isInRole = um.IsInRole(user.Id, "Admin");


            if (// User is admin)
            {

            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }



    }

}

UPDATE:

Well it all works fine if i use: var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); in the new authentication attribute that i've created... Not really sure though what's the best practice to use ApplicationDbContext() with Ado.net data model created later

Arsalan Qaiser
  • 426
  • 2
  • 7
  • 26

2 Answers2

0

It seems that the ApplicationUser identity isn't part of your current context WeatherAppDbEntities. You should implement it to your context.

public class WeatherAppDbEntities : IdentityDbContext<ApplicationUser>
{
    public WeatherAppDbEntities()
        : base("DefaultConnection")
    {
    }
}
lucky
  • 12,734
  • 4
  • 24
  • 46
  • I'm not really fluent in ASPNET identity thing, but what I've done was basically I created an MVC application with authorization and I let it create a db for me, then I added one additional table to this DB.... Anyways, I tried that and doesn't seem to work neither, same error: public partial class WeatherAppDbEntities : IdentityDbContext // DbContext { public WeatherAppDbEntities() : base("name=WeatherAppDbEntities") { } ...... } "throwIfV1Schema" is not found though Says comment is too long, sec. – KlapekApokalipsy Jan 27 '18 at 08:55
  • The error that i'm getting is: "The entity type ApplicationUser is not part of the model for the current context" – KlapekApokalipsy Jan 27 '18 at 09:25
  • When I go with "DefaultConnection" i'm getting: System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: 'The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConn.... – KlapekApokalipsy Jan 27 '18 at 09:45
0

Like Stormcloak mentioned it seems that you have two or more DbContexts and therefore you are using more then one databases or connection strings.When creating Asp.Net MVC projects, tamplate comes with some models and controlers, as well as connection string named "DefaultConnection". Visual studio uses SQL Server Express and with connection string it generates database that will store information about users, so when you create your own database (" WeatherAppDb") you are basically working with two databases. How to prevent this?

1. When creating MVC project check Web.config file for <connectionStrings> tag, if you find something like tihs

 <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MyMVCProject-20180127104017.mdf;Initial Catalog=aspnet-MyMVCProject-20180127104017;Integrated Security=True"
      providerName="System.Data.SqlClient" />

<add name="WeatherAppDbConnectionString" connectionString="Data Source=(LocalDb)\SQLEXPRESS;;Initial Catalog=WeatherAppDb;Integrated Security=True"
      providerName="System.Data.SqlClient" />

The easiest way would be to delete "Default Connection" connection string and rename your "Weather App DbConnectionString" to "Default Connection", so you would be left with just this

//renamed from WeatherAppDbConnectionString to Default Connection
     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\SQLEXPRESS;;Initial Catalog=WeatherAppDb;Integrated Security=True"
      providerName="System.Data.SqlClient" />

2. Once you have done first step, just go to your WeatherAppDbEntities and as StormCloack stated make sure you have "Default Connection" here

public class WeatherAppDbEntities : IdentityDbContext<ApplicationUser>
        {
            public WeatherAppDbEntities()
                : base("DefaultConnection")
            {
            }
        }

As far as your code, maybe there could be a problem also but not sure, i've modified a little.

   WeatherAppDbEntities db = new WeatherAppDbEntities();
            var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));               
            var user = db.Users.Find(username);
Djordje
  • 437
  • 1
  • 12
  • 24
  • Sorry but comment space isn't enough to explain all this... I put it here: https://codeshare.io/5MJjZq That didn't work though.... – KlapekApokalipsy Jan 27 '18 at 10:38
  • cant you see that you are using two [connection strings](https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings) with diffrent name? have you tried changing web.config? – Djordje Jan 27 '18 at 11:11
  • Well, Sir, That's how VS generated all of this for me after adding ADO.NET data model...Here's entire application: https://files.fm/u/qwffvz7x Sorry, not really sure how to proceed even though it might seem obvious to you... – KlapekApokalipsy Jan 27 '18 at 11:16
  • 1
    Well it all works fine if i use: var um = new UserManager(new UserStore(new ApplicationDbContext())); in the new authentication attribute that i've created... Not really sure though what's the best practice to use ApplicationDbContext() with Ado.net data model created later... anyway, thanks for trying i'll mark your answer correct anyway. – KlapekApokalipsy Jan 27 '18 at 12:15
  • Just as i was about to start your app :D , just tell me why do you need to use your authentication (`MyNewAuthentication`)? – Djordje Jan 27 '18 at 12:27
  • To access the data using external services, well the idea is to grant access to /api/weather only to those who are registered and have "Admin" rights so then later I can actually access this data through fiddler querying: GET: http://localhost:11353/api/weather User-Agent: Fiddler Host: localhost:11353 Authorization: Basic c2FkMkBzYWQucGw6MTIzcXc= and also so that weather data can be accessed for logged in users despide of role If there is a better approach to doing this, please advise... – KlapekApokalipsy Jan 27 '18 at 12:31
  • I have never had a chance to use it, but i've think you should read more about [Microsoft Authentication](https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/external-authentication-services) because they have done pretty great job and provided support for many features, and also try to avoid multiple connection strings whenever you can, so modify this to use either "WeatherAppDbEntities" or "Default connection" . If i think of some example for authentification, i will update my answer – Djordje Jan 27 '18 at 12:49