在过去的 7 天里,我尝试使用OpenIdConnect.Server
资源所有者流程设置 ASP.NET 5 WebApi。
[Authorize]
我在生成令牌和访问受保护的操作方面或多或少是成功的。
但是,当我尝试访问时this.User.Identity.Claims
,它是空的。我现在正在使用 ASP.NET 5,beta6(升级到最新的 beta7 并等待它的正式发布时遇到问题)
在 Startup.cs 我得到以下内容:
public void ConfigureServices(IServiceCollection services)
{
services.AddCaching();
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<AuthContext>(options =>
{
options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString"));
});
services.AddIdentity<AuthUser, AuthRole>(
options => options.User = new Microsoft.AspNet.Identity.UserOptions
{
RequireUniqueEmail = true,
UserNameValidationRegex = "^[a-zA-Z0-9@_\\.-]+$"
})
.AddEntityFrameworkStores<AuthContext, Guid>()
.AddDefaultTokenProviders();
services.ConfigureCors(configure =>
{
configure.AddPolicy("CorsPolicy", builder =>
{
builder.WithOrigins("http:/localhost/", "http://win2012.bludev.com/");
});
});
services.AddScoped<IAuthRepository, AuthRepository>();
}
public void Configure(IApplicationBuilder app)
{
var factory = app.ApplicationServices.GetRequiredService<ILoggerFactory>();
factory.AddConsole();
app.UseStaticFiles();
app.UseOAuthBearerAuthentication(options =>
{
options.Authority = "http://win2012.bludev.com/api/auth/";
options.Audience = "http://win2012.bludev.com/";
options.AutomaticAuthentication = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
RequireExpirationTime = true,
RequireSignedTokens = true,
RoleClaimType = ClaimTypes.Role,
NameClaimType = ClaimTypes.NameIdentifier,
ValidateActor = true,
ValidateAudience = false,
ValidateIssuer = true,
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
ValidateSignature = true,
ValidAudience = "http://win2012.bludev.com/",
ValidIssuer = "http://win2012.bludev.com/"
};
});
app.UseOpenIdConnectServer(options =>
{
options.Issuer = new Uri("http://win2012.bludev.com/api/auth/");
options.AllowInsecureHttp = true;
options.AuthorizationEndpointPath = PathString.Empty;
options.Provider = new AuthorizationProvider();
options.ApplicationCanDisplayErrors = true;
// Note: in a real world app, you'd probably prefer storing the X.509 certificate
// in the user or machine store. To keep this sample easy to use, the certificate
// is extracted from the Certificate.pfx file embedded in this assembly.
options.UseCertificate(
assembly: typeof(Startup).GetTypeInfo().Assembly,
resource: "AuthExample.Certificate.pfx",
password: "Owin.Security.OpenIdConnect.Server");
});
app.UseIdentity();
app.UseMvc();
}
}
我使用app.UseOAuthBearerAuthentication
是因为我无法app.UseOpenIdConnectAuthentication
工作,我会在控制台中得到这个:
请求:/admin/user/ 警告:[Microsoft.AspNet.Authentication.OpenIdConnect.OpenIdConnectAuthenticationMiddleware] OIDCH_0004:OpenIdConnectAuthenticationHandler:message.State 为空或为空。请求:/.well-known/openid-configuration 警告:[Microsoft.AspNet.Authentication.OpenIdConnect.OpenIdConnectAuthenticationMiddleware] OIDCH_0004:OpenIdConnectAuthenticationHandler:message.State 为空或为空。
超时后出现异常
错误:[Microsoft.AspNet.Server.WebListener.MessagePump] ProcessRequestAsync System.InvalidOperationException:IDX10803:无法创建以从以下位置获取配置:' http ://win2012.bludev.com/api/auth/.well-known/openid -配置'。在 Microsoft.IdentityModel.Logging.LogHelper.Throw(String message, Type exceptionType, EventLevel logLevel, Exception innerException) at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.d__24.MoveNext() --- 从上一个位置结束堆栈跟踪抛出异常的地方---在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 的 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) ...
有了这个配置UseOpenIdConnectAuthentication
app.UseOpenIdConnectAuthentication(options =>
{
options.AuthenticationScheme = OpenIdConnectAuthenticationDefaults.AuthenticationScheme;
options.Authority = "http://win2012.bludev.com/api/auth/";
options.Audience = "http://win2012.bludev.com/";
options.Resource = "http://win2012.bludev.com/";
options.AutomaticAuthentication = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
RequireExpirationTime = true,
RequireSignedTokens = true,
RoleClaimType = ClaimTypes.Role,
NameClaimType = ClaimTypes.NameIdentifier,
ValidateActor = true,
ValidateAudience = false,
ValidateIssuer = true,
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
ValidateSignature = true
};
});
所以真正的问题是:
- 如何让资源所有者流程处理索赔
ValidateLifetime = true
或者ValidateAudience = true
会抛出异常并导致 Http Code 500 响应而没有打印错误。- 如何将身份验证失败转换为有意义的 400/403 代码和 json 或 xml 响应(取决于客户端首选项)以显示给用户?(在这种情况下,JavaScript 是客户端)?