IdentityServer3 使用参考令牌
IdentityServer3 using reference tokens
我有一个使用参考令牌设置的项目,它正在运行。但是现在我收到一个错误:
Error returned from introspection endpoint: Not Found
这很奇怪,因为我认为我没有改变任何东西。
我找不到任何文档来帮助解决这个问题:(
我已经这样设置了我的应用程序:
public static class Config
{
/// <summary>
/// Configures identity server
/// </summary>
public static void ConfigureIdentityServer(this IAppBuilder app, CormarConfig config)
{
// Create our options
var identityServerOptions = new IdentityServerOptions
{
SiteName = "API",
SigningCertificate = LoadCertificate(),
IssuerUri = "https://api-test.azurewebsites.net",
LoggingOptions = new LoggingOptions
{
EnableHttpLogging = true,
EnableWebApiDiagnostics = true,
EnableKatanaLogging = true,
WebApiDiagnosticsIsVerbose = true
},
Factory = new IdentityServerServiceFactory().Configure(config),
Endpoints = new EndpointOptions()
{
EnableAccessTokenValidationEndpoint = false
},
// Disable when live
EnableWelcomePage = true
};
// Setup our auth path
app.Map("/identity", idsrvApp => { idsrvApp.UseIdentityServer(identityServerOptions); });
}
/// <summary>
/// Configures the identity server to use token authentication
/// </summary>
public static void ConfigureIdentityServerTokenAuthentication(this IAppBuilder app, HttpConfiguration config)
{
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://api-test.azurewebsites.net/identity",
DelayLoadMetadata = true,
//ValidationMode = ValidationMode.Both,
RequiredScopes = new[] {"api"},
ClientId = "api",
ClientSecret = "8at?7nAtaB!E"
});
}
/// <summary>
/// Configures Autofac DI/IoC
/// </summary>
public static IContainer ConfigureAutofac(this IAppBuilder app, HttpConfiguration config, Assembly assembly)
{
// Create our container
var builder = new ContainerBuilder();
// You can register controllers all at once using assembly scanning...
builder.RegisterApiControllers(assembly);
// Register our module
builder.RegisterModule(new CormarModule(app));
// Filters
builder.RegisterType<LogExceptionFilterAttribute>().AsWebApiExceptionFilterFor<IHttpController>();
builder.RegisterWebApiFilterProvider(config);
// Build
var container = builder.Build();
// Lets Web API know it should locate services using the AutofacWebApiDependencyResolver
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
// Return our container
return container;
}
/// <summary>
/// Loads the certificate
/// </summary>
/// <returns></returns>
private static X509Certificate2 LoadCertificate()
{
var certPath = $"{AppDomain.CurrentDomain.BaseDirectory}App_Data\idsrv3test.pfx";
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, "asdf", false);
certStore.Close();
// If we are on azure, get the actual self signed certificate, otherwise return the test one
return certCollection.Count > 0 ? certCollection[0] : new X509Certificate2(certPath, "idsrv3test");
}
/// <summary>
/// Configure the identity service factory with custom services
/// </summary>
/// <returns></returns>
private static IdentityServerServiceFactory Configure(this IdentityServerServiceFactory factory, CormarConfig config)
{
var serviceOptions = new EntityFrameworkServiceOptions {ConnectionString = config.SqlConnectionString};
factory.RegisterOperationalServices(serviceOptions);
factory.RegisterConfigurationServices(serviceOptions);
factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService {AllowAll = true}); // Allow all domains to access authentication
factory.Register(new Registration<DbContext>(dr => dr.ResolveFromAutofacOwinLifetimeScope<DbContext>()));
factory.UserService = new Registration<IUserService>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IUserService>());
factory.ClientStore = new Registration<IClientStore>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IClientStore>());
factory.ScopeStore = new Registration<IScopeStore>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IScopeStore>());
return factory;
}
}
这些是从 Startup.cs 中调用的,如下所示:
public void Configuration(IAppBuilder app)
{
// Cors must be first, or it will not work
app.UseCors(CorsOptions.AllowAll);
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
// Get our configuration
var config = new HttpConfiguration();
var assembly = Assembly.GetExecutingAssembly();
var container = app.ConfigureAutofac(config, assembly);
var scope = config.DependencyResolver.GetRootLifetimeScope();
ConfigureWebApi(config);
// Create our logger and assign it to
ConfigureLogger(scope.Resolve<CormarConfig>());
// Register the Autofac middleware FIRST. This also adds
// Autofac-injected middleware registered with the container.
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(config);
app.ConfigureIdentityServer(scope.Resolve<CormarConfig>());
app.ConfigureIdentityServerTokenAuthentication(config);
app.UseWebApi(config);
}
当我尝试从 /connect/token 获取我的访问令牌时,它起作用了。我得到了我的令牌,但如果我随后尝试访问任何控制器,我总是会收到 401 访问被拒绝并且我的日志显示上面的错误加上:
invalid bearer token received
有谁知道我是否遗漏了一步?
我已将 AccessTokenValidation nuget 添加到我的项目中,但不知道我还应该用它做什么(如果有的话)。
请帮助
好的,所以收到的错误与原因无关。
在这种情况下,原因是 IdentityServerBearerTokenAuthenticationOptions.Authority 不正确。它必须是身份服务器的实际路径。
将其更改为正确的路径解决了我的问题,一切都开始工作了。
我有一个使用参考令牌设置的项目,它正在运行。但是现在我收到一个错误:
Error returned from introspection endpoint: Not Found
这很奇怪,因为我认为我没有改变任何东西。 我找不到任何文档来帮助解决这个问题:( 我已经这样设置了我的应用程序:
public static class Config
{
/// <summary>
/// Configures identity server
/// </summary>
public static void ConfigureIdentityServer(this IAppBuilder app, CormarConfig config)
{
// Create our options
var identityServerOptions = new IdentityServerOptions
{
SiteName = "API",
SigningCertificate = LoadCertificate(),
IssuerUri = "https://api-test.azurewebsites.net",
LoggingOptions = new LoggingOptions
{
EnableHttpLogging = true,
EnableWebApiDiagnostics = true,
EnableKatanaLogging = true,
WebApiDiagnosticsIsVerbose = true
},
Factory = new IdentityServerServiceFactory().Configure(config),
Endpoints = new EndpointOptions()
{
EnableAccessTokenValidationEndpoint = false
},
// Disable when live
EnableWelcomePage = true
};
// Setup our auth path
app.Map("/identity", idsrvApp => { idsrvApp.UseIdentityServer(identityServerOptions); });
}
/// <summary>
/// Configures the identity server to use token authentication
/// </summary>
public static void ConfigureIdentityServerTokenAuthentication(this IAppBuilder app, HttpConfiguration config)
{
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://api-test.azurewebsites.net/identity",
DelayLoadMetadata = true,
//ValidationMode = ValidationMode.Both,
RequiredScopes = new[] {"api"},
ClientId = "api",
ClientSecret = "8at?7nAtaB!E"
});
}
/// <summary>
/// Configures Autofac DI/IoC
/// </summary>
public static IContainer ConfigureAutofac(this IAppBuilder app, HttpConfiguration config, Assembly assembly)
{
// Create our container
var builder = new ContainerBuilder();
// You can register controllers all at once using assembly scanning...
builder.RegisterApiControllers(assembly);
// Register our module
builder.RegisterModule(new CormarModule(app));
// Filters
builder.RegisterType<LogExceptionFilterAttribute>().AsWebApiExceptionFilterFor<IHttpController>();
builder.RegisterWebApiFilterProvider(config);
// Build
var container = builder.Build();
// Lets Web API know it should locate services using the AutofacWebApiDependencyResolver
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
// Return our container
return container;
}
/// <summary>
/// Loads the certificate
/// </summary>
/// <returns></returns>
private static X509Certificate2 LoadCertificate()
{
var certPath = $"{AppDomain.CurrentDomain.BaseDirectory}App_Data\idsrv3test.pfx";
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, "asdf", false);
certStore.Close();
// If we are on azure, get the actual self signed certificate, otherwise return the test one
return certCollection.Count > 0 ? certCollection[0] : new X509Certificate2(certPath, "idsrv3test");
}
/// <summary>
/// Configure the identity service factory with custom services
/// </summary>
/// <returns></returns>
private static IdentityServerServiceFactory Configure(this IdentityServerServiceFactory factory, CormarConfig config)
{
var serviceOptions = new EntityFrameworkServiceOptions {ConnectionString = config.SqlConnectionString};
factory.RegisterOperationalServices(serviceOptions);
factory.RegisterConfigurationServices(serviceOptions);
factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService {AllowAll = true}); // Allow all domains to access authentication
factory.Register(new Registration<DbContext>(dr => dr.ResolveFromAutofacOwinLifetimeScope<DbContext>()));
factory.UserService = new Registration<IUserService>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IUserService>());
factory.ClientStore = new Registration<IClientStore>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IClientStore>());
factory.ScopeStore = new Registration<IScopeStore>(dr => dr.ResolveFromAutofacOwinLifetimeScope<IScopeStore>());
return factory;
}
}
这些是从 Startup.cs 中调用的,如下所示:
public void Configuration(IAppBuilder app)
{
// Cors must be first, or it will not work
app.UseCors(CorsOptions.AllowAll);
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
// Get our configuration
var config = new HttpConfiguration();
var assembly = Assembly.GetExecutingAssembly();
var container = app.ConfigureAutofac(config, assembly);
var scope = config.DependencyResolver.GetRootLifetimeScope();
ConfigureWebApi(config);
// Create our logger and assign it to
ConfigureLogger(scope.Resolve<CormarConfig>());
// Register the Autofac middleware FIRST. This also adds
// Autofac-injected middleware registered with the container.
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(config);
app.ConfigureIdentityServer(scope.Resolve<CormarConfig>());
app.ConfigureIdentityServerTokenAuthentication(config);
app.UseWebApi(config);
}
当我尝试从 /connect/token 获取我的访问令牌时,它起作用了。我得到了我的令牌,但如果我随后尝试访问任何控制器,我总是会收到 401 访问被拒绝并且我的日志显示上面的错误加上:
invalid bearer token received
有谁知道我是否遗漏了一步?
我已将 AccessTokenValidation nuget 添加到我的项目中,但不知道我还应该用它做什么(如果有的话)。 请帮助
好的,所以收到的错误与原因无关。 在这种情况下,原因是 IdentityServerBearerTokenAuthenticationOptions.Authority 不正确。它必须是身份服务器的实际路径。 将其更改为正确的路径解决了我的问题,一切都开始工作了。