我试图使用OpenIddict从asp.net核心应用程序获取令牌。
当我从我的终端请求令牌时,我得到了这个例外:
System.InvalidOperationException:无法使用表' OpenIddictApplications'在架构''对于实体' OpenIddictApplication'因为它被用于另一个实体。
在Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message)
在Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.EnsureDistinctTableNames(IModel模型)
在Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel模型)
在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext上下文,IConventionSetBuilder conventionSetBuilder,IModelValidator验证器)
在System.Collections.Concurrent.ConcurrentDictionary 2.GetOrAdd(TKey key, Func
2 valueFactory)
在Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
在Microsoft.EntityFrameworkCore.Internal.LazyRef 1.get_Value()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.<>c.<AddQuery>b__1_3(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure
1访问者)
在Microsoft.EntityFrameworkCore.DbContext.get_QueryProvider()
在Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.<.ctor>b__3_0()
at Microsoft.EntityFrameworkCore.Internal.LazyRef
1.get_Value()
在Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable
1源,表达式`1谓词)
at C:\ Users \ Enrique_Garcia \ Desktop \ OpenID \ OpenID \ Controllers \ AuthorizeController.cs中的OpenID.Controllers.AuthorizeController.d__2.MoveNext():第35行
---从抛出异常的先前位置开始的堆栈跟踪结束---
在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)
在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__27.MoveNext()
---从抛出异常的先前位置开始的堆栈跟踪结束---
在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)
在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__25.MoveNext()
---从抛出异常的先前位置开始的堆栈跟踪结束---
在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&amp; next,Scope&amp; scope,Object&amp; state,Boolean&amp; isCompleted)
在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__22.MoveNext()
---从抛出异常的先前位置开始的堆栈跟踪结束---
在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
....
已经看到this,但我没有使用Asp.Net Identity
ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddDbContext<UniverContext>(options =>
{
options.UseSqlServer(Configuration["Data:ConnectionString"]);
options.UseOpenIddict();
});
services.AddOpenIddict(options =>
{
options.AddEntityFrameworkCoreStores<UniverContext>();
options.AddMvcBinders();
options.EnableTokenEndpoint("/connect/token");
options.AllowPasswordFlow().AllowRefreshTokenFlow();
options.SetAccessTokenLifetime(TimeSpan.FromMinutes(1));
options.SetRefreshTokenLifetime(TimeSpan.FromMinutes(2));
options.DisableHttpsRequirement();
options.UseJsonWebTokens();
options.AddEphemeralSigningKey();
});
}
配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseDeveloperExceptionPage();
app.UseOpenIddict();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = "http://localhost:5000",
Audience = "resource_server",
RequireHttpsMetadata = false,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = OpenIdConnectConstants.Claims.Subject,
RoleClaimType = OpenIdConnectConstants.Claims.Role
}
});
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvcWithDefaultRoute();
app.UseWelcomePage();
}
先谢谢。
这是我的UniverContext类:
public partial class UniverContext : DbContext
{
public virtual DbSet<Alumno> Alumno { get; set; }
public virtual DbSet<AlumnoInscrito> AlumnoInscrito { get; set; }
public virtual DbSet<Genero> Genero { get; set; }
public virtual DbSet<OfertaEducativa> OfertaEducativa { get; set; }
public virtual DbSet<OpenIddictApplications> OpenIddictApplications { get; set; }
public virtual DbSet<OpenIddictAuthorizations> OpenIddictAuthorizations { get; set; }
public virtual DbSet<OpenIddictScopes> OpenIddictScopes { get; set; }
public virtual DbSet<OpenIddictTokens> OpenIddictTokens { get; set; }
public virtual DbSet<Usuario> Usuario { get; set; }
public virtual DbSet<UsuarioDetalle> UsuarioDetalle { get; set; }
public UniverContext(DbContextOptions<UniverContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//modelBuilder.UseOpenIddict();
modelBuilder.Entity<Alumno>(entity =>
{
entity.HasIndex(e => e.GeneroId)
.HasName("IX_Alumno_GeneroId");
entity.Property(e => e.AlumnoId).ValueGeneratedNever();
entity.Property(e => e.GeneroId).HasDefaultValueSql("0");
entity.Property(e => e.Nombre).IsRequired();
entity.HasOne(d => d.Genero)
.WithMany(p => p.Alumno)
.HasForeignKey(d => d.GeneroId);
});
modelBuilder.Entity<AlumnoInscrito>(entity =>
{
entity.HasKey(e => new { e.AlumnoId, e.OfertaEducativaId })
.HasName("PK_AlumnoInscrito");
entity.HasIndex(e => e.OfertaEducativaId)
.HasName("IX_AlumnoInscrito_OfertaEducativaId");
entity.HasOne(d => d.Alumno)
.WithMany(p => p.AlumnoInscrito)
.HasForeignKey(d => d.AlumnoId);
entity.HasOne(d => d.OfertaEducativa)
.WithMany(p => p.AlumnoInscrito)
.HasForeignKey(d => d.OfertaEducativaId);
entity.HasOne(d => d.Usuario)
.WithMany(p => p.AlumnoInscrito)
.HasForeignKey(d => d.UsuarioId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK_AlumnoInscrito_Usuario");
});
modelBuilder.Entity<Genero>(entity =>
{
entity.Property(e => e.GeneroId).ValueGeneratedNever();
entity.Property(e => e.Descripcion).IsRequired();
});
modelBuilder.Entity<OfertaEducativa>(entity =>
{
entity.Property(e => e.OfertaEducativaId).ValueGeneratedNever();
entity.Property(e => e.Descripcion).IsRequired();
});
modelBuilder.Entity<OpenIddictApplications>(entity =>
{
entity.HasIndex(e => e.ClientId)
.HasName("IX_OpenIddictApplications_ClientId")
.IsUnique();
entity.Property(e => e.Id).HasMaxLength(450);
entity.Property(e => e.ClientId)
.IsRequired()
.HasMaxLength(450);
});
modelBuilder.Entity<OpenIddictAuthorizations>(entity =>
{
entity.HasIndex(e => e.ApplicationId)
.HasName("IX_OpenIddictAuthorizations_ApplicationId");
entity.Property(e => e.Id).HasMaxLength(450);
entity.Property(e => e.ApplicationId).HasMaxLength(450);
entity.HasOne(d => d.Application)
.WithMany(p => p.OpenIddictAuthorizations)
.HasForeignKey(d => d.ApplicationId);
});
modelBuilder.Entity<OpenIddictScopes>(entity =>
{
entity.Property(e => e.Id).HasMaxLength(450);
});
modelBuilder.Entity<OpenIddictTokens>(entity =>
{
entity.HasIndex(e => e.ApplicationId)
.HasName("IX_OpenIddictTokens_ApplicationId");
entity.HasIndex(e => e.AuthorizationId)
.HasName("IX_OpenIddictTokens_AuthorizationId");
entity.Property(e => e.Id).HasMaxLength(450);
entity.Property(e => e.ApplicationId).HasMaxLength(450);
entity.Property(e => e.AuthorizationId).HasMaxLength(450);
entity.HasOne(d => d.Application)
.WithMany(p => p.OpenIddictTokens)
.HasForeignKey(d => d.ApplicationId);
entity.HasOne(d => d.Authorization)
.WithMany(p => p.OpenIddictTokens)
.HasForeignKey(d => d.AuthorizationId);
});
modelBuilder.Entity<Usuario>(entity =>
{
entity.Property(e => e.UsuarioId).HasDefaultValueSql("0");
entity.Property(e => e.Nombre).IsRequired();
entity.Property(e => e.Paterno)
.IsRequired()
.HasDefaultValueSql("N''");
});
modelBuilder.Entity<UsuarioDetalle>(entity =>
{
entity.HasKey(e => e.UsuarioId)
.HasName("PK_UsuarioDetalle");
entity.Property(e => e.UsuarioId).ValueGeneratedNever();
entity.Property(e => e.Password)
.IsRequired()
.HasColumnType("varchar(50)");
entity.HasOne(d => d.Usuario)
.WithOne(p => p.UsuarioDetalle)
.HasForeignKey<UsuarioDetalle>(d => d.UsuarioId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK_UsuarioDetalle_Usuario");
});
}
}
我的csproj文件包含的是:
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
<AspNetContribOpenIdExtensionsVersion>1.0.0-*</AspNetContribOpenIdExtensionsVersion>
<OpenIddictVersion>1.0.0-*</OpenIddictVersion>
<PackageTargetFallback>portable-net45+win8</PackageTargetFallback>
<PackageReference Include="AspNet.Security.OAuth.Validation" Version="1.0.0-rtm-0255" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" />
<PackageReference Include="OpenIddict" Version="$(OpenIddictVersion)" />
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="$(OpenIddictVersion)" />
<PackageReference Include="OpenIddict.Mvc" Version="$(OpenIddictVersion)" />
软件包openiddict版本是1.0.0-beta2-0607
我正在尝试并且它的工作原理是这是我的AuthorizationController:
if (request.Username != "email@email.com")
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The username/password couple is invalid"
});
}
if (request.Password != "123456+")
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The username/password couple is invalid"
});
}
但是在Startup类中注册我的DbContext之后,我试图使用数据库用户:
var user = _context.Usuario.SingleOrDefault(x => x.UsuarioId == int.Parse(request.Username));
在这一行中,我得到了所描述的错误。
如果您想查看我的AuthorizationController,我创建了一个repo,谢谢。
答案 0 :(得分:2)
这个例外听起来很清楚:OpenIddict在您调用options.AddOpenIddict()
时注册默认实体,但您自己的DbContext
定义了最终使用相同表名的不同实体(OpenIddictApplications
/ { {1}} / OpenIddictAuthorizations
/ OpenIddictScopes
),由于实体类型不同,被EntityFramework视为非法操作。
您有两种方法可以解决这个问题:
OpenIddictTokens
vs OpenIddictApplication
)。OpenIddictApplications