4

在过去的 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
    };

});

所以真正的问题是:

  1. 如何让资源所有者流程处理索赔
  2. ValidateLifetime = true或者ValidateAudience = true会抛出异常并导致 Http Code 500 响应而没有打印错误。
  3. 如何将身份验证失败转换为有意义的 400/403 代码和 json 或 xml 响应(取决于客户端首选项)以显示给用户?(在这种情况下,JavaScript 是客户端)?
4

1 回答 1

2

app.UseOpenIdConnectAuthentication()(依赖于OpenIdConnectAuthenticationMiddleware)仅用于支持交互式流程(代码/隐式/混合),不能与资源所有者密码凭据授予类型一起使用。由于您只想验证访问令牌,请app.UseOAuthBearerAuthentication()改用。

有关 ASP.NET 5 中不同 OpenID Connect/OAuth2 中间件的更多信息,请参阅此 SO 答案:配置授权服务器端点

如何让资源所有者流程处理索赔

您使用的全部OpenIdConnectServerMiddleware内容基于声明。

如果您在序列化特定声明时遇到问题,请记住,除了ClaimTypes.NameIdentifier默认情况下,身份和访问令牌中的所有声明都不会序列化,因为客户端应用程序和用户代理都可以读取它们。为避免泄露机密数据,您需要明确destination指出您希望在何处序列化声明:

// This claim will be only serialized in the access token.
identity.AddClaim(ClaimTypes.Name, username, OpenIdConnectConstants.Destinations.AccessToken);

// This claim will be serialized in both the identity and the access tokens.
identity.AddClaim(ClaimTypes.Surname, "Doe",
    OpenIdConnectConstants.Destinations.AccessToken,
    OpenIdConnectConstants.Destinations.IdentityToken););

ValidateLifetime = true 或 ValidateAudience = true 将引发异常并导致 Http Code 500 响应而没有打印错误。

如何将身份验证失败转换为有意义的 400/403 代码和 json 或 xml 响应(取决于客户端首选项)以显示给用户?(在这种情况下,JavaScript 是客户端)?

这就是 OIDC 客户端中间件(由 MSFT 管理)当前默认工作的方式,但最终会得到修复。您可以查看此 GitHub 票证的解决方法:https ://github.com/aspnet/Security/issues/411

于 2015-08-30T18:28:07.670 回答