Пример #1
0
        private async Task <bool> AuthenticateRequest(AuthenticationSchemes scheme, TcpListenerWebSocketContext context)
        {
            var chal = scheme == AuthenticationSchemes.Basic
                       ? AuthenticationChallenge.CreateBasicChallenge(Realm).ToBasicString()
                       : scheme == AuthenticationSchemes.Digest
                         ? AuthenticationChallenge.CreateDigestChallenge(Realm).ToDigestString()
                         : null;

            if (chal == null)
            {
                await context.Close(HttpStatusCode.Forbidden).ConfigureAwait(false);

                return(false);
            }

            var retry                = -1;
            var schm                 = scheme.ToString();
            var realm                = Realm;
            var credFinder           = UserCredentialsFinder;
            Func <Task <bool> > auth = () => Task.FromResult(false);

            auth = async() =>
            {
                var auth1 = auth;
                retry++;
                if (retry > 99)
                {
                    await context.Close(HttpStatusCode.Forbidden).ConfigureAwait(false);

                    return(false);
                }

                var res = await context.GetHeader("Authorization").ConfigureAwait(false);

                if (res == null || !res.StartsWith(schm, StringComparison.OrdinalIgnoreCase))
                {
                    context.SendAuthenticationChallenge(chal);
                    return(await auth1().ConfigureAwait(false));
                }

                await context.SetUser(scheme, realm, credFinder).ConfigureAwait(false);

                if (!context.IsAuthenticated)
                {
                    context.SendAuthenticationChallenge(chal);
                    return(await auth1().ConfigureAwait(false));
                }

                return(true);
            };

            return(await auth().ConfigureAwait(false));
        }