使用AspNet.Security.OpenIdConnect.Server(RC2)发出令牌 - 无效的客户端?

时间:2016-06-08 21:01:09

标签: asp.net-core openid-connect aspnet-contrib

我能够在RC1中拉这个。 OpenIdConnectServerProvider发生了很大的变化。

我对资源所有者流感兴趣,所以我的AuthorizationProvider看起来像这样:

    public sealed class AuthorizationProvider : OpenIdConnectServerProvider
    {

        public override Task MatchEndpoint(MatchEndpointContext context)
        {
            if (context.Options.AuthorizationEndpointPath.HasValue &&
                context.Request.Path.StartsWithSegments(context.Options.AuthorizationEndpointPath))
            {
                context.MatchesAuthorizationEndpoint();
            }

            return Task.FromResult<object>(null);
        }

        public override async Task ValidateAuthorizationRequest(ValidateAuthorizationRequestContext context)
        {
            context.Validate();
            await Task.FromResult<object>(null);
        }

        public override async Task ValidateTokenRequest(ValidateTokenRequestContext context)
        {                
            if (!context.Request.IsAuthorizationCodeGrantType() &&
                !context.Request.IsRefreshTokenGrantType() &&
                !context.Request.IsPasswordGrantType())
            {
                context.Reject(
                    error: "unsupported_grant_type",
                    description: "Only authorization code, refresh token, and ROPC grant types " +
                                 "are accepted by this authorization server");
            }

            /* This is where the problem is. This context.Validate()
               will automatically return a 400, server_error, with
               message "An internal server error occurred."

               If I commented this out, I will get a 400, invalid_client.

               If I put in an arbitrary client like "any_client", it
               goes to GrantResourceOwnerCredentials, as I expect.
               However, I get a 500 with no explanation when it executes.
               See the function below for more details.
            */
            context.Validate();
            await Task.FromResult<object>(null);
        }

        public override Task HandleUserinfoRequest(HandleUserinfoRequestContext context)
        {                
            context.SkipToNextMiddleware();

            return Task.FromResult<object>(null);
        }

        public override async Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context)
        {
             MYDbContext db = context.HttpContext.RequestServices.GetRequiredService<MyDbContext>();
             UserManager<MyUser> UM = context.HttpContext.RequestServices.GetRequiredService<UserManager<MyUser>>();

             MyUser user = await UM.FindByNameAsync(context.Request.Username);

             if (user == null)
             {
                context.Reject(
                   error: "user_not_found",
                   description: "User not found");

                return;
             }

             bool passwordsMatch = await UM.CheckPasswordAsync(user, context.Request.Password);

             if (!passwordsMatch)
             {
                 context.Reject(
                    error: "invalid_credentials",
                    description: "Password is incorrect");

                 return;
             }

             var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);

            identity.AddClaim(ClaimTypes.Name, user.UserName, "id_token token");

            /* I set the breakpoint on this line, and the execution
               does not hit this breakpoint. I immediately get a 500.
               My output says 'System.ArgumentException' in
               AspNet.Security.OpenIdConnect.Extensions.dll
            */
            List<string> roles = (await UM.GetRolesAsync(user)).ToList();

            roles.ForEach(role =>
            {
                identity.AddClaim(ClaimTypes.Role, role, "id_token token");
            });

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity),
                                                  new AuthenticationProperties(),
                                                  context.Options.AuthenticationScheme);

            ticket.SetResources(new[] { "mlm_resource_server" });
            ticket.SetAudiences(new[] { "mlm_resource_server" });
            ticket.SetScopes(new[] { "defaultscope" });

            context.Validate(ticket);
        }
    }

顺便说一下,我正试图在Fiddler上运行它:

POST /token HTTP/1.1
Host: localhost:56785
Content-Type: application/x-www-form-urlencoded

username=user&password=pw&grant_type=password

当密码不正确时,我得到预期的400拒绝,但是当密码正确时,我得到500.

我错过了什么?我构建该用户身份的方式现在是不正确的吗?我应该覆盖另一个功能吗?

注意 - 我没有提供我的启动文件,因为我觉得它无关紧要。如果绝对需要,我会稍后发布。

1 个答案:

答案 0 :(得分:1)

如果您已启用日志记录,则您已立即了解所发生的情况:OpenID Connect服务器中间件不允许您将令牌请求标记为&#34;已完全验证&#34;当请求中缺少client_id时:

if (context.IsValidated && string.IsNullOrEmpty(request.ClientId)) {
    Logger.LogError("The token request was validated but the client_id was not set.");

    return await SendTokenResponseAsync(request, new OpenIdConnectMessage {
        Error = OpenIdConnectConstants.Errors.ServerError,
        ErrorDescription = "An internal server error occurred."
    });
}

如果您想使客户端身份验证可选,请改为呼叫context.Skip()

请注意,您的提供商存在一些问题:

ValidateAuthorizationRequest没有验证任何内容,这是可怕,因为任何redirect_uri都会被视为有效(=一个巨大的开放重定向漏洞)。幸运的是,由于您只对ROPC资助感兴趣,因此您可能无法实施任何互动流程。我建议您删除此方法(您也可以删除MatchEndpoint)。

ValidateTokenRequest中的初始授权检查有问题,因为您在调用context.Reject()后不会停止执行代码,这最终会导致context.Validate()被调用。

identity.AddClaim(ClaimTypes.Name, user.UserName, "id_token token")不再是有效的语法。 ArgumentException可能是由此检查引起的:

if (destinations.Any(destination => destination.Contains(" "))) {
    throw new ArgumentException("Destinations cannot contain spaces.", nameof(destinations));
}

而是使用它:

identity.AddClaim(ClaimTypes.Name, user.UserName,
    OpenIdConnectConstants.Destinations.AccessToken,
    OpenIdConnectConstants.Destinations.IdentityToken);

如果您仍然不确定您的提供商应该是什么样子,请不要犹豫,看看这些具体样本: