0

I'm getting errors on relations not having a key. (I posted full errors below). But these errors only occur when I hit the /Token endpoint which is using some prebuilt Microsoft code to run it. I did notice that to get my Token endpoint working I had to add a "DefaultConnection" string to my web.config file which indicates to me that it is using a different context. How can I set the DbContext that this code will use? Because my DbContext seems to be working fine. I can query tables and return results on web pages. I just can't seem to hit the Token endpoint without receiving errors.

Startup.Auth.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Owin;
using ImmsLinkWebAdmin.Providers;
using ImmsLinkWebAdmin.Models;

namespace ImmsLinkWebAdmin
{
    public partial class Startup
    {
        static Startup()
        {
            PublicClientId = "self";

            UserManagerFactory = () => new UserManager<AspNetUser>(new UserStore<AspNetUser>());

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };
        }

        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static Func<UserManager<AspNetUser>> UserManagerFactory { get; set; }

        public static string PublicClientId { get; private set; }

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication();
        }
    }
}


HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcYW5kcmV3cnVzdVxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEzXFByb2plY3RzXEltbXNMaW5rV2ViQWRtaW5cSW1tc0xpbmtXZWJBZG1pblxUb2tlbg==?=
X-Powered-By: ASP.NET
Date: Sun, 08 Jun 2014 16:14:01 GMT
Content-Length: 16437

<!DOCTYPE html>
<html>
    <head>
        <title>One or more validation errors were detected during model generation:<br><br>Microsoft.AspNet.Identity.EntityFramework.Environment: : EntityType 'Environment' has no key defined. Define the key for this EntityType.<br>Microsoft.AspNet.Identity.EntityFramework.SubscriberRegistrySetting: : EntityType 'SubscriberRegistrySetting' has no key defined. Define the key for this EntityType.<br>Environments: EntityType: EntitySet 'Environments' is based on type 'Environment' that has no keys defined.<br>SubscriberRegistrySettings: EntityType: EntitySet 'SubscriberRegistrySettings' is based on type 'SubscriberRegistrySetting' that has no keys defined.<br></title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>One or more validation errors were detected during model generation:<br><br>Microsoft.AspNet.Identity.EntityFramework.Environment: : EntityType 'Environment' has no key defined. Define the key for this EntityType.<br>Microsoft.AspNet.Identity.EntityFramework.SubscriberRegistrySetting: : EntityType 'SubscriberRegistrySetting' has no key defined. Define the key for this EntityType.<br>Environments: EntityType: EntitySet 'Environments' is based on type 'Environment' that has no keys defined.<br>SubscriberRegistrySettings: EntityType: EntitySet 'SubscriberRegistrySettings' is based on type 'SubscriberRegistrySetting' that has no keys defined.<br></i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

            <br><br>

            <b> Exception Details: </b>System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:<br><br>Microsoft.AspNet.Identity.EntityFramework.Environment: : EntityType 'Environment' has no key defined. Define the key for this EntityType.<br>Microsoft.AspNet.Identity.EntityFramework.SubscriberRegistrySetting: : EntityType 'SubscriberRegistrySetting' has no key defined. Define the key for this EntityType.<br>Environments: EntityType: EntitySet 'Environments' is based on type 'Environment' that has no keys defined.<br>SubscriberRegistrySettings: EntityType: EntitySet 'SubscriberRegistrySettings' is based on type 'SubscriberRegistrySetting' that has no keys defined.<br><br><br>

            <b>Source Error:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

Line 38:             using (UserManager&lt;AspNetUser&gt; userManager = _userManagerFactory())
Line 39:             {
<font color=red>Line 40:                 var user = await userManager.FindAsync(context.UserName, context.Password);
</font>Line 41: 
Line 42:                 if (user == null)</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <b> Source File: </b> c:\Users\AndrewRusu\Documents\Visual Studio 2013\Projects\ImmsLinkWebAdmin\ImmsLinkWebAdmin\Providers\ApplicationOAuthProvider.cs<b> &nbsp;&nbsp; Line: </b> 40
            <br><br>

            <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[ModelValidationException: One or more validation errors were detected during model generation:

Microsoft.AspNet.Identity.EntityFramework.Environment: : EntityType &#39;Environment&#39; has no key defined. Define the key for this EntityType.
Microsoft.AspNet.Identity.EntityFramework.SubscriberRegistrySetting: : EntityType &#39;SubscriberRegistrySetting&#39; has no key defined. Define the key for this EntityType.
Environments: EntityType: EntitySet &#39;Environments&#39; is based on type &#39;Environment&#39; that has no keys defined.
SubscriberRegistrySettings: EntityType: EntitySet &#39;SubscriberRegistrySettings&#39; is based on type &#39;SubscriberRegistrySetting&#39; that has no keys defined.
]
   System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate() +259
   System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) +447
   System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +103
   System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +143
   System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +171
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +594
   System.Data.Entity.Internal.InternalContext.Initialize() +31
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +39
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +137
   System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +38
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +99
   System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
   Microsoft.AspNet.Identity.EntityFramework.UserStore`1.FindByNameAsync(String userName) +1100
   Microsoft.AspNet.Identity.&lt;FindByNameAsync&gt;d__d.MoveNext() +231
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   Microsoft.AspNet.Identity.&lt;FindAsync&gt;d__15.MoveNext() +540
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   ImmsLinkWebAdmin.Providers.&lt;GrantResourceOwnerCredentials&gt;d__0.MoveNext() in c:\Users\AndrewRusu\Documents\Visual Studio 2013\Projects\ImmsLinkWebAdmin\ImmsLinkWebAdmin\Providers\ApplicationOAuthProvider.cs:40
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Security.OAuth.&lt;InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync&gt;d__3a.MoveNext() +862
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   Microsoft.Owin.Security.OAuth.&lt;InvokeTokenEndpointAsync&gt;d__1e.MoveNext() +2335
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Security.OAuth.&lt;InvokeAsync&gt;d__0.MoveNext() +1728
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   Microsoft.Owin.Security.Infrastructure.&lt;Invoke&gt;d__0.MoveNext() +664
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Security.Infrastructure.&lt;Invoke&gt;d__0.MoveNext() +937
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Security.Infrastructure.&lt;Invoke&gt;d__0.MoveNext() +937
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
   Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155
</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18446

            </font>

    </body>
</html>
<!-- 
[ModelValidationException]: One or more validation errors were detected during model generation:

Microsoft.AspNet.Identity.EntityFramework.Environment: : EntityType &#39;Environment&#39; has no key defined. Define the key for this EntityType.
Microsoft.AspNet.Identity.EntityFramework.SubscriberRegistrySetting: : EntityType &#39;SubscriberRegistrySetting&#39; has no key defined. Define the key for this EntityType.
Environments: EntityType: EntitySet &#39;Environments&#39; is based on type &#39;Environment&#39; that has no keys defined.
SubscriberRegistrySettings: EntityType: EntitySet &#39;SubscriberRegistrySettings&#39; is based on type &#39;SubscriberRegistrySetting&#39; that has no keys defined.

   at System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate()
   at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.Initialize()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
   at Microsoft.AspNet.Identity.EntityFramework.UserStore`1.FindByNameAsync(String userName)
   at Microsoft.AspNet.Identity.UserManager`1.<FindByNameAsync>d__d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNet.Identity.UserManager`1.<FindAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at ImmsLinkWebAdmin.Providers.ApplicationOAuthProvider.<GrantResourceOwnerCredentials>d__0.MoveNext() in c:\Users\AndrewRusu\Documents\Visual Studio 2013\Projects\ImmsLinkWebAdmin\ImmsLinkWebAdmin\Providers\ApplicationOAuthProvider.cs:line 40
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.<InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync>d__3a.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.<InvokeTokenEndpointAsync>d__1e.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.<InvokeAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow()
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
JayPrime2012
  • 2,502
  • 4
  • 22
  • 39

1 Answers1

0

Never mind. I figured out that I can pass my db context to the UserStore constructor, else it will use a default dbcontext (which was what was causing all my problem.)

JayPrime2012
  • 2,502
  • 4
  • 22
  • 39