在過去的7天中,我嘗試使用OpenIdConnect.Server
和資源所有者流設置ASP.NET 5 WebApi。在ASP.NET 5中使用OpenIdConnect.Server的聲明
我在生成令牌和訪問[Authorize]
受保護的操作方面或多或少成功。
但是,當我嘗試訪問this.User.Identity.Claims
時,它是空的。我使用ASP.NET 5,beta6現在(在遇到問題時升級到最新的β7的,等待它的正式發佈)
在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 = "^[[email protected]_\\.-]+$"
})
.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
工作,所有我會得到這是在控制檯:
要求:/管理/用戶/警告: [Microsoft.AspNet.Authentication.OpenIdConnect.OpenIdConnectAuthentica tionMiddleware] OI DCH_0004:OpenIdConnectAuthenticationHandler: message.State爲空或空。請求: /.well-known/openid-configuration警告: [Microsoft.AspNet.Authentication.OpenIdConnect.OpenIdConnectAuthentica tionMiddleware] OIDCH_0004:OpenIdConnectAuthenticationHandler: message.State是空值或空白。
且超時後一個異常
錯誤:[Microsoft.AspNet.Server.WebListener.MessagePump] ProcessRequestAsync System.InvalidOperationException:IDX10803:無法 創建從獲得configura和灰: 'http://win2012.bludev.com/api/auth/.well-known/openid-configuration' 。在Microsoft.IdentityModel.Logging.LogHelper.Throw(字符串 消息類型excep tionType,EventLevel日誌級別,異常 的InnerException)在 Microsoft.IdentityModel.Protocols.ConfigurationManager`1.d__24.MoveNext() ---堆完從先前的位置在那裏異常被拋出在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot ification跟蹤---在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任務 任務)(任務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代碼500響應,從而打印出錯誤的工作。- 如何將身份驗證失敗轉化爲有意義的400/403代碼和json或xml響應(取決於客戶端首選項)以供用戶顯示? (在這種情況下JavaScript是客戶端)?
'InvalidOperationException'是由'http:// win2012.bludev.com/api/auth /'沒有服務器引起的。當OAuth2承載中間件嘗試下載提供程序的配置元數據時,它會崩潰並返回一個異常。 – Pinpoint