Exemple #1
0
        public async Task <IUser> Auth(string userName, string userPassword)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                {
                    throw new ArgumentNullException(nameof(userName));
                }
                if (string.IsNullOrEmpty(userPassword))
                {
                    throw new ArgumentNullException(nameof(userPassword));
                }

                var user = await this.FindUser(userName);

                if (user == null)
                {
                    return(null);
                }

                var isValid = user.CheckPassword(userPassword, _encryptionKey);
                return(isValid ? user : null);
            }
            catch (Exception ex)
            {
                _log?.WriteError(nameof(UserRepository), nameof(Auth), userName, null, ex);
                throw;
            }
        }
Exemple #2
0
 /// <summary>
 /// Logs an error to one or more configured destinations, including the internal error cache (if enabled).
 /// </summary>
 public void LogError(Exception ex)
 {
     try
     {
         if (ex is ThreadAbortException)
         {
             throw ex;
         }
         else
         {
             _logger?.WriteError(ex);
             foreach (IErrorLogger logger in _errorLoggers)
             {
                 logger.LogError(ex);
             }
         }
     }
     catch (ThreadAbortException tae)
     {
         throw tae;
     }
     catch
     {
     }
 }
Exemple #3
0
        private static async Task ExecuteJobAsync(string id, IScheduledJob job, ILogger logger, bool tracingEnabled)
        {
            Stopwatch sw = tracingEnabled ? new Stopwatch() : null;

            try
            {
                sw?.Start();
                await job.ExecuteAsync();

                sw?.Stop();
                if (tracingEnabled)
                {
                    logger?.WriteInformation($"Job(Id: {id} , DisplayName: {job.DisplayName})已执行,耗时:{sw.ElapsedMilliseconds} 毫秒。");
                }
            }
            catch (Exception ex)
            {
                sw?.Stop();
                logger?.WriteError($"Job(Id: {id} , DisplayName: {job.DisplayName})执行作业时发生错误。", ex);
                ex.ThrowIfNecessary();
            }
            finally
            {
                IDisposable disposable = job as IDisposable;
                disposable?.Dispose();
            }
        }
Exemple #4
0
 /// <summary>
 /// 处理服务器错误(仅在第一次启动时候抛出异常,watch 回掉中发生错误错误认为节点无变化)。
 /// </summary>
 private void HandleError(bool firstLoad, string error, Exception causeException = null)
 {
     _logger?.WriteError(error, causeException);
     if (!_environment.IsDevelopmentEnvironment && firstLoad)
     {
         throw new ConfigurationException(error, causeException);
     }
 }
Exemple #5
0
        private static IScheduledJob CreateScheduledJob(Type jobType, ILogger logger, IServiceScope s)
        {
            try
            {
                IScheduledJob job = (IScheduledJob)ActivatorUtilities.CreateInstance(s.ServiceProvider, jobType);
                return(job);
            }
            catch (InvalidOperationException ex)
            {
                logger?.WriteError($"创建 Job 类型 {jobType.FullName} 实例时发生错误。", ex);
            }
            catch (Exception ex)
            {
                logger?.WriteError($"创建 Job 类型 {jobType.FullName} 实例时发生错误。", ex);
                ex.ThrowIfNecessary();
            }

            return(null);
        }
Exemple #6
0
        private IEnumerable <Type> GetLoadableTypes(Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }

            try
            {
                return(assembly.GetTypes());
            }
            catch (ReflectionTypeLoadException e)
            {
                _logger?.WriteError(e.Message);
                return(e.Types.Where(t => t != null));
            }
        }
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark)
        {
            logger.WriteLineInfo($"BuildScript: {generateResult.ArtifactsPaths.BuildScriptFilePath}");

            var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(generateResult.ArtifactsPaths.ProgramCodePath));

            var compilationOptions = new CSharpCompilationOptions(
                 outputKind: OutputKind.ConsoleApplication,
                 optimizationLevel: OptimizationLevel.Release,
                 allowUnsafe: true,
                 platform: GetPlatform(benchmark.Job.Platform),
                 deterministic: true);

            var references = RoslynGenerator
                .GetAllReferences(benchmark)
                .Select(assembly => AssemblyMetadata.CreateFromFile(assembly.Location))
                .Concat(FrameworkAssembliesMetadata.Value)
                .Distinct()
                .Select(uniqueMetadata => uniqueMetadata.GetReference());

            var compilation = CSharpCompilation
                .Create(assemblyName: Path.GetFileName(generateResult.ArtifactsPaths.ExecutablePath))
                .AddSyntaxTrees(syntaxTree)
                .WithOptions(compilationOptions)
                .AddReferences(references);

            using (var executable = File.Create(generateResult.ArtifactsPaths.ExecutablePath))
            {
                var emitResult = compilation.Emit(executable);

                if(emitResult.Success)
                {
                    return BuildResult.Success(generateResult);
                }

                foreach (var diagnostic in emitResult.Diagnostics
                    .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error))
                {
                    logger.WriteError($"{diagnostic.Id}: {diagnostic.GetMessage()}");
                }

                return BuildResult.Failure(generateResult);
            }
        }
Exemple #8
0
        public RestService(INancyBootstrapper bootstrapper, IServiceConfig config, ILogger logger, ShortlistQueryRepository shortlistQueryRepository)
        {
            if (bootstrapper == null) { throw new ArgumentNullException(nameof(bootstrapper)); }
            if (config == null) { throw new ArgumentNullException(nameof(config)); }
            if (logger == null) { throw new ArgumentNullException(nameof(logger)); }
            if (shortlistQueryRepository == null) { throw new ArgumentNullException(nameof(shortlistQueryRepository)); }

            _shortlistQueryRepository = shortlistQueryRepository;
            var nancyConfig = new HostConfiguration();
            nancyConfig.UrlReservations.CreateAutomatically = true;

            _nancyService = new NancyHost(bootstrapper, nancyConfig, new Uri(config.RestUrl));
            nancyConfig.UnhandledExceptionCallback = (exception) =>
            {
                var message = String.Format("Uncaught exception: {0}", exception.Message);
                logger.WriteError(message);
            };
            if (config.QueueConsumer)
            {
                SetupEventQueueListener(config, logger);
            }
        }
Exemple #9
0
        IntPtr INativeMemoryProvider.AllocateBytes(long numberOfBytes)
        {
            var cashed = _free.Find(md => md.NumberOfBytes == numberOfBytes);

            if (cashed != null)
            {
                _free.Remove(cashed);
                _logger?.WriteStatus($"\t\t\t\tReUsing {numberOfBytes}");
                return(cashed.Ptr);
            }

            var ptr        = AllocateMemory(numberOfBytes);
            var descriptor = new MemoryDescriptor(ptr, numberOfBytes);

            _allocated.Add(descriptor);

            var stack = MemoryUtils.ParseStackTrace();

            var gigaBytes = numberOfBytes / (1024.0 * 1024 * 1024);

            _logger?.WriteError($"Allocating {gigaBytes:######0.0000} GiB ({numberOfBytes} bytes), ptr:{ptr} at {stack[7]}");

            return(ptr);
        }
Exemple #10
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                var query  = Request.Query;
                var values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var requestPrefix = Request.Scheme + "://" + this.GetHostName();
                var redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("redirect_uri", redirectUri),
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                    new KeyValuePair <string, string>("client_secret", Options.ClientSecret)
                };

                // Request the token
                var tokenResponse = await _httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));

                tokenResponse.EnsureSuccessStatusCode();
                var text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response    = JsonConvert.DeserializeObject <dynamic>(text);
                var     accessToken = (string)response.access_token;
                var     expires     = (string)response.expires_in;

                // Get the LinkedIn user
                var userInfoEndpoint = UserInfoEndpoint
                                       + "~:(" + string.Join(",", Options.ProfileFields.Distinct().ToArray()) + ")"
                                       + "?oauth2_access_token=" + Uri.EscapeDataString(accessToken);
                var userRequest = new HttpRequestMessage(HttpMethod.Get, userInfoEndpoint);
                userRequest.Headers.Add("x-li-format", "json");
                var graphResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                var user = JObject.Parse(text);

                var context = new LinkedInAuthenticatedContext(Context, user, accessToken, expires)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.GivenName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.GivenName, context.GivenName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FamilyName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Surname, context.FamilyName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Name, XmlSchemaString, Options.AuthenticationType));
                    context.Identity.AddClaim(new Claim("urn:linkedin:name", context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Industry))
                {
                    context.Identity.AddClaim(new Claim("urn:linkedin:industry", context.Industry, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Positions))
                {
                    context.Identity.AddClaim(new Claim("urn:linkedin:positions", context.Positions, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Summary))
                {
                    context.Identity.AddClaim(new Claim("urn:linkedin:summary", context.Summary, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Headline))
                {
                    context.Identity.AddClaim(new Claim("urn:linkedin:headline", context.Headline, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:linkedin:url", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.AccessToken))
                {
                    context.Identity.AddClaim(new Claim("urn:linkedin:accesstoken", context.AccessToken, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Exemple #11
0
        public void Initalize()
        {
            var runtimePath = _aspNet5Paths.RuntimePath;

            _context.RuntimePath = runtimePath.Value;

            if (!ScanForProjects())
            {
                // No ASP.NET 5 projects found so do nothing
                _logger.WriteInformation("No project.json based projects found");
                return;
            }

            if (_context.RuntimePath == null)
            {
                // There is no default k found so do nothing
                _logger.WriteInformation("No default runtime found");
                _emitter.Emit(EventTypes.Error, runtimePath.Error);
                return;
            }

            var wh = new ManualResetEventSlim();

            _designTimeHostManager.Start(_context.HostId, port =>
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(new IPEndPoint(IPAddress.Loopback, port));

                var networkStream = new NetworkStream(socket);

                _logger.WriteInformation("Connected");

                _context.DesignTimeHostPort = port;

                _context.Connection = new ProcessingQueue(networkStream, _logger);

                _context.Connection.OnReceive += m =>
                {
                    var project = _context.Projects[m.ContextId];

                    if (m.MessageType == "ProjectInformation")
                    {
                        var val = m.Payload.ToObject <ProjectMessage>();

                        project.Name               = val.Name;
                        project.GlobalJsonPath     = val.GlobalJsonPath;
                        project.Configurations     = val.Configurations;
                        project.Commands           = val.Commands;
                        project.ProjectSearchPaths = val.ProjectSearchPaths;

                        this._emitter.Emit(EventTypes.ProjectChanged, new ProjectInformationResponse()
                        {
                            AspNet5Project = new AspNet5Project(project)
                        });

                        var unprocessed = project.ProjectsByFramework.Keys.ToList();

                        foreach (var frameworkData in val.Frameworks)
                        {
                            unprocessed.Remove(frameworkData.FrameworkName);

                            var frameworkProject = project.ProjectsByFramework.GetOrAdd(frameworkData.FrameworkName, framework =>
                            {
                                return(new FrameworkProject(project, framework));
                            });

                            var id = frameworkProject.ProjectId;

                            if (_workspace.CurrentSolution.ContainsProject(id))
                            {
                                continue;
                            }
                            else
                            {
                                var projectInfo = ProjectInfo.Create(
                                    id,
                                    VersionStamp.Create(),
                                    val.Name + "+" + frameworkData.ShortName,
                                    val.Name,
                                    LanguageNames.CSharp,
                                    project.Path);

                                _workspace.AddProject(projectInfo);
                                _context.WorkspaceMapping[id] = frameworkProject;
                            }

                            lock (frameworkProject.PendingProjectReferences)
                            {
                                var reference = new Microsoft.CodeAnalysis.ProjectReference(id);

                                foreach (var referenceId in frameworkProject.PendingProjectReferences)
                                {
                                    _workspace.AddProjectReference(referenceId, reference);
                                }

                                frameworkProject.PendingProjectReferences.Clear();
                            }
                        }

                        // Remove old projects
                        foreach (var frameworkName in unprocessed)
                        {
                            FrameworkProject frameworkProject;
                            project.ProjectsByFramework.TryRemove(frameworkName, out frameworkProject);
                            _workspace.RemoveProject(frameworkProject.ProjectId);
                        }
                    }
                    // This is where we can handle messages and update the
                    // language service
                    else if (m.MessageType == "References")
                    {
                        // References as well as the dependency graph information
                        var val = m.Payload.ToObject <ReferencesMessage>();

                        var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName];
                        var projectId        = frameworkProject.ProjectId;

                        var metadataReferences = new List <MetadataReference>();
                        var projectReferences  = new List <Microsoft.CodeAnalysis.ProjectReference>();

                        var removedFileReferences    = frameworkProject.FileReferences.ToDictionary(p => p.Key, p => p.Value);
                        var removedRawReferences     = frameworkProject.RawReferences.ToDictionary(p => p.Key, p => p.Value);
                        var removedProjectReferences = frameworkProject.ProjectReferences.ToDictionary(p => p.Key, p => p.Value);

                        foreach (var file in val.FileReferences)
                        {
                            if (removedFileReferences.Remove(file))
                            {
                                continue;
                            }

                            var metadataReference = _metadataFileReferenceCache.GetMetadataReference(file);
                            frameworkProject.FileReferences[file] = metadataReference;
                            metadataReferences.Add(metadataReference);
                        }

                        foreach (var rawReference in val.RawReferences)
                        {
                            if (removedRawReferences.Remove(rawReference.Key))
                            {
                                continue;
                            }

                            var metadataReference = MetadataReference.CreateFromImage(rawReference.Value);
                            frameworkProject.RawReferences[rawReference.Key] = metadataReference;
                            metadataReferences.Add(metadataReference);
                        }

                        foreach (var projectReference in val.ProjectReferences)
                        {
                            if (removedProjectReferences.Remove(projectReference.Path))
                            {
                                continue;
                            }

                            int projectReferenceContextId;
                            if (!_context.ProjectContextMapping.TryGetValue(projectReference.Path, out projectReferenceContextId))
                            {
                                projectReferenceContextId = AddProject(projectReference.Path);
                            }

                            var referencedProject = _context.Projects[projectReferenceContextId];

                            var referencedFrameworkProject = referencedProject.ProjectsByFramework.GetOrAdd(projectReference.Framework.FrameworkName,
                                                                                                            framework =>
                            {
                                return(new FrameworkProject(referencedProject, framework));
                            });

                            var projectReferenceId = referencedFrameworkProject.ProjectId;

                            if (_workspace.CurrentSolution.ContainsProject(projectReferenceId))
                            {
                                projectReferences.Add(new Microsoft.CodeAnalysis.ProjectReference(projectReferenceId));
                            }
                            else
                            {
                                lock (referencedFrameworkProject.PendingProjectReferences)
                                {
                                    referencedFrameworkProject.PendingProjectReferences.Add(projectId);
                                }
                            }

                            referencedFrameworkProject.ProjectDependeees[project.Path] = projectId;

                            frameworkProject.ProjectReferences[projectReference.Path] = projectReferenceId;
                        }

                        foreach (var reference in metadataReferences)
                        {
                            _workspace.AddMetadataReference(projectId, reference);
                        }

                        foreach (var projectReference in projectReferences)
                        {
                            _workspace.AddProjectReference(projectId, projectReference);
                        }

                        foreach (var pair in removedProjectReferences)
                        {
                            _workspace.RemoveProjectReference(projectId, new Microsoft.CodeAnalysis.ProjectReference(pair.Value));
                            frameworkProject.ProjectReferences.Remove(pair.Key);

                            // TODO: Update the dependee's list
                        }

                        foreach (var pair in removedFileReferences)
                        {
                            _workspace.RemoveMetadataReference(projectId, pair.Value);
                            frameworkProject.FileReferences.Remove(pair.Key);
                        }

                        foreach (var pair in removedRawReferences)
                        {
                            _workspace.RemoveMetadataReference(projectId, pair.Value);
                            frameworkProject.RawReferences.Remove(pair.Key);
                        }
                    }
                    else if (m.MessageType == "Dependencies")
                    {
                        var val = m.Payload.ToObject <DependenciesMessage>();
                        var unresolvedDependencies = val.Dependencies.Values
                                                     .Where(dep => dep.Type == "Unresolved");

                        if (unresolvedDependencies.Any())
                        {
                            _logger.WriteInformation("Project {0} has these unresolved references: {1}", project.Path, string.Join(", ", unresolvedDependencies.Select(d => d.Name)));
                            _emitter.Emit(EventTypes.UnresolvedDependencies, new UnresolvedDependenciesMessage()
                            {
                                FileName = project.Path,
                                UnresolvedDependencies = unresolvedDependencies.Select(d => new PackageDependency()
                                {
                                    Name = d.Name, Version = d.Version
                                })
                            });
                            _packagesRestoreTool.Run(project);
                        }
                    }
                    else if (m.MessageType == "CompilerOptions")
                    {
                        // Configuration and compiler options
                        var val = m.Payload.ToObject <CompilationOptionsMessage>();

                        var projectId = project.ProjectsByFramework[val.Framework.FrameworkName].ProjectId;

                        var options = val.CompilationOptions.CompilationOptions;

                        var specificDiagnosticOptions = options.SpecificDiagnosticOptions
                                                        .ToDictionary(p => p.Key, p => (ReportDiagnostic)p.Value);

                        var csharpOptions = new CSharpCompilationOptions(
                            outputKind: (OutputKind)options.OutputKind,
                            optimizationLevel: (OptimizationLevel)options.OptimizationLevel,
                            platform: (Platform)options.Platform,
                            generalDiagnosticOption: (ReportDiagnostic)options.GeneralDiagnosticOption,
                            warningLevel: options.WarningLevel,
                            allowUnsafe: options.AllowUnsafe,
                            concurrentBuild: options.ConcurrentBuild,
                            specificDiagnosticOptions: specificDiagnosticOptions
                            );

                        var parseOptions = new CSharpParseOptions(val.CompilationOptions.LanguageVersion,
                                                                  preprocessorSymbols: val.CompilationOptions.Defines);

                        _workspace.SetCompilationOptions(projectId, csharpOptions);
                        _workspace.SetParseOptions(projectId, parseOptions);
                    }
                    else if (m.MessageType == "Sources")
                    {
                        // The sources to feed to the language service
                        var val = m.Payload.ToObject <SourcesMessage>();

                        project.SourceFiles = val.Files;

                        var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName];
                        var projectId        = frameworkProject.ProjectId;

                        var unprocessed = new HashSet <string>(frameworkProject.Documents.Keys);

                        foreach (var file in val.Files)
                        {
                            if (unprocessed.Remove(file))
                            {
                                continue;
                            }

                            using (var stream = File.OpenRead(file))
                            {
                                var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
                                var id         = DocumentId.CreateNewId(projectId);
                                var version    = VersionStamp.Create();

                                frameworkProject.Documents[file] = id;

                                var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));
                                _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
                            }
                        }

                        foreach (var file in unprocessed)
                        {
                            var docId = frameworkProject.Documents[file];
                            frameworkProject.Documents.Remove(file);
                            _workspace.RemoveDocument(docId);
                        }

                        frameworkProject.Loaded = true;
                    }
                    else if (m.MessageType == "Error")
                    {
                        var val = m.Payload.ToObject <Microsoft.Framework.DesignTimeHost.Models.OutgoingMessages.ErrorMessage>();
                        _logger.WriteError(val.Message);
                    }

                    if (project.ProjectsByFramework.Values.All(p => p.Loaded))
                    {
                        wh.Set();
                    }
                };

                // Start the message channel
                _context.Connection.Start();

                // Initialize the ASP.NET 5 projects
                Initialize();
            });

            wh.Wait();
        }
Exemple #12
0
        /// <summary>
        /// Invoked to process incoming authentication messages.
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            // Allow login to be constrained to a specific path.
            //if (Options.CallbackPath.HasValue && Options.CallbackPath != (Request.PathBase + Request.Path))
            //{
            //    return null;
            //}

            var SamlMessage = await SamlMessageFromRequest();

            if (SamlMessage == null || !SamlMessage.IsSignInMessage())
            {
                return(null);
            }

            ExceptionDispatchInfo authFailedEx = null;

            try {
                var messageReceivedNotification = new MessageReceivedNotification <SamlMessage, SamlAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = SamlMessage
                };
                await Options.Notifications.MessageReceived(messageReceivedNotification);

                if (messageReceivedNotification.HandledResponse)
                {
                    return(GetHandledResponseTicket());
                }
                if (messageReceivedNotification.Skipped)
                {
                    return(null);
                }

                //if (SamlMessage.Wresult == null) {
                //    _logger.WriteWarning("Received a sign-in message without a WResult.");
                //    return null;
                //}

                string token = SamlMessage.GetToken();
                if (string.IsNullOrWhiteSpace(token))
                {
                    _logger.WriteWarning("Received a sign-in message without a token.");
                    return(null);
                }

                var securityTokenReceivedNotification = new SecurityTokenReceivedNotification <SamlMessage, SamlAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = SamlMessage
                };
                await Options.Notifications.SecurityTokenReceived(securityTokenReceivedNotification);

                if (securityTokenReceivedNotification.HandledResponse)
                {
                    return(GetHandledResponseTicket());
                }
                if (securityTokenReceivedNotification.Skipped)
                {
                    return(null);
                }


                // Copy and augment to avoid cross request race conditions for updated configurations.

                ClaimsPrincipal principal      = null;
                ClaimsIdentity  claimsIdentity = principal.Identity as ClaimsIdentity;

                // Retrieve our cached redirect uri
                // string state = SamlMessage.Wctx;
                // WsFed allows for uninitiated logins, state may be missing.
                AuthenticationProperties properties = null;// GetPropertiesFromWctx(state);
                AuthenticationTicket     ticket     = new AuthenticationTicket(claimsIdentity, properties);

                //if (Options.UseTokenLifetime) {
                //    // Override any session persistence to match the token lifetime.
                //    DateTime issued = parsedToken.ValidFrom;
                //    if (issued != DateTime.MinValue) {
                //        ticket.Properties.IssuedUtc = issued.ToUniversalTime();
                //    }
                //    DateTime expires = parsedToken.ValidTo;
                //    if (expires != DateTime.MinValue) {
                //        ticket.Properties.ExpiresUtc = expires.ToUniversalTime();
                //    }
                //    ticket.Properties.AllowRefresh = false;
                //}

                var securityTokenValidatedNotification = new SecurityTokenValidatedNotification <SamlMessage, SamlAuthenticationOptions>(Context, Options)
                {
                    AuthenticationTicket = ticket,
                    ProtocolMessage      = SamlMessage,
                };

                await Options.Notifications.SecurityTokenValidated(securityTokenValidatedNotification);

                if (securityTokenValidatedNotification.HandledResponse)
                {
                    return(GetHandledResponseTicket());
                }
                if (securityTokenValidatedNotification.Skipped)
                {
                    return(null);
                }
                // Flow possible changes
                ticket = securityTokenValidatedNotification.AuthenticationTicket;

                return(ticket);
            }
            catch (Exception exception) {
                // We can't await inside a catch block, capture and handle outside.
                authFailedEx = ExceptionDispatchInfo.Capture(exception);
            }

            if (authFailedEx != null)
            {
                _logger.WriteError("Exception occurred while processing message: ", authFailedEx.SourceException);

                // Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the notification.
                //if (Options.RefreshOnIssuerKeyNotFound && authFailedEx.SourceException.GetType().Equals(typeof(SecurityTokenSignatureKeyNotFoundException))) {
                //    Options.ConfigurationManager.RequestRefresh();
                //}

                var authenticationFailedNotification = new AuthenticationFailedNotification <SamlMessage, SamlAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = SamlMessage,
                    Exception       = authFailedEx.SourceException
                };
                await Options.Notifications.AuthenticationFailed(authenticationFailedNotification);

                if (authenticationFailedNotification.HandledResponse)
                {
                    return(GetHandledResponseTicket());
                }
                if (authenticationFailedNotification.Skipped)
                {
                    return(null);
                }

                authFailedEx.Throw();
            }

            return(null);
        }
Exemple #13
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try {
                string code  = null;
                string state = null;

                var query  = Request.Query;
                var values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var requestPrefix = "https://" + Request.Host;                 // Schema must be HTTPS
                var redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("client_assertion_type",
                                                      "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
                    new KeyValuePair <string, string>("client_assertion", Options.AppSecret),
                    new KeyValuePair <string, string>("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
                    new KeyValuePair <string, string>("assertion", code),
                    new KeyValuePair <string, string>("redirect_uri", redirectUri)
                };

                // Request the token
                var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.Endpoints.TokenEndpoint);
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                requestMessage.Content = new FormUrlEncodedContent(body);
                var tokenResponse = await _httpClient.SendAsync(requestMessage);

                tokenResponse.EnsureSuccessStatusCode();
                var text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response     = JsonConvert.DeserializeObject <dynamic>(text);
                var     accessToken  = (string)response.access_token;
                var     refreshToken = (string)response.refresh_token;
                var     expiresIn    = (int)response.expires_in;

                // Get the Visual Studio Online user
                var userRequest = new HttpRequestMessage(HttpMethod.Get, Options.Endpoints.UserInfoEndpoint);
                userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var userResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled);

                userResponse.EnsureSuccessStatusCode();
                text = await userResponse.Content.ReadAsStringAsync();

                var user = JObject.Parse(text);

                var context = new VisualStudioAuthenticatedContext(Context, user, accessToken, expiresIn, refreshToken)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Alias))
                {
                    context.Identity.AddClaim(new Claim("urn:vso:alias", context.Alias, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            } catch (Exception ex) {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Exemple #14
0
        protected override void PreRestart(Exception reason, object message)
        {
            _logger.WriteError($"{Self.Path.Name} PreRestart: {reason}");

            base.PreRestart(reason, message);
        }
Exemple #15
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                var query  = Request.Query;
                var values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                // Check for error
                if (Request.Query.Get("error") != null)
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var requestPrefix = Request.Scheme + "://" + Request.Host;
                var redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                    new KeyValuePair <string, string>("client_secret", Options.ClientSecret),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("redirect_uri", redirectUri)
                };

                var secret       = Options.ClientId + ":" + Options.ClientSecret;
                var secretBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret));

                var tokenRequest = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint);
                tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", secretBase64);
                tokenRequest.Content = new FormUrlEncodedContent(body);

                // Request the token
                var tokenResponse = await _httpClient.SendAsync(tokenRequest);

                tokenResponse.EnsureSuccessStatusCode();
                var text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response    = JsonConvert.DeserializeObject <dynamic>(text);
                var     accessToken = (string)response.access_token;
                var     scope       = (string)response.scope;

                // Get the Slack user
                var userRequest = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint + "?token=" + Uri.EscapeDataString(accessToken));

                var userResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled);

                userResponse.EnsureSuccessStatusCode();
                text = await userResponse.Content.ReadAsStringAsync();

                var user = JObject.Parse(text);

                var context = new SlackAuthenticatedContext(Context, user, accessToken, scope)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };
                if (!string.IsNullOrEmpty(context.UserId))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.TeamId))
                {
                    context.Identity.AddClaim(new Claim("urn:slack:teamid", context.TeamId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.TeamName))
                {
                    context.Identity.AddClaim(new Claim("urn:slack:teamname", context.TeamName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.TeamUrl))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Webpage, context.TeamUrl, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Exemple #16
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string token = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("token");
                if (values != null && values.Count == 1)
                {
                    token = values[0];
                }

                string stateCookieKey = Constants.StatePrefix + Options.AuthenticationType;
                string stateCookie    = Request.Cookies[stateCookieKey];
                if (string.IsNullOrWhiteSpace(stateCookie))
                {
                    _logger.WriteWarning("{0} cookie not found.", stateCookie);
                    return(null);
                }

                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Secure   = Request.IsSecure
                };

                Response.Cookies.Delete(stateCookieKey, cookieOptions);

                properties = Options.StateDataFormat.Unprotect(stateCookie);
                if (properties == null)
                {
                    return(null);
                }

                // Request the token
                ActivityDetails activityDetails = await _yotiClient.GetActivityDetailsAsync(token);

                if (activityDetails.Outcome != ActivityOutcome.Success)
                {
                    // TODO: Check how this is handled
                    throw new HttpRequestException();
                }

                var context = new YotiAuthenticatedContext(Context, activityDetails.UserProfile);

                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrEmpty(context.User.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.User.Id, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (context.User.Selfie != null)
                {
                    context.Identity.AddClaim(new Claim("selfie", Convert.ToBase64String(context.User.Selfie.Data), context.User.Selfie.Type.ToString(), Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.GivenNames))
                {
                    context.Identity.AddClaim(new Claim("given_names", context.User.GivenNames, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.FamilyName))
                {
                    context.Identity.AddClaim(new Claim("family_name", context.User.FamilyName, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.MobileNumber))
                {
                    context.Identity.AddClaim(new Claim("phone_number", context.User.MobileNumber, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.EmailAddress))
                {
                    context.Identity.AddClaim(new Claim("email_address", context.User.EmailAddress, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (context.User.DateOfBirth != null)
                {
                    context.Identity.AddClaim(new Claim("date_of_birth", context.User.DateOfBirth.Value.ToString("yyyy-MM-dd"), ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Address))
                {
                    context.Identity.AddClaim(new Claim("postal_address", context.User.Address, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Gender))
                {
                    context.Identity.AddClaim(new Claim("gender", context.User.Gender, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Nationality))
                {
                    context.Identity.AddClaim(new Claim("nationality", context.User.Nationality, ClaimValueTypes.String, Options.AuthenticationType));
                }

                foreach (var attributeName in context.User.OtherAttributes.Keys)
                {
                    var attributeValue = context.User.OtherAttributes[attributeName];
                    context.Identity.AddClaim(new Claim(attributeName, attributeValue.ToString(), attributeValue.Type.ToString(), Options.AuthenticationType));
                }

                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
        internal static bool GenerateSgenCommandLineParameters(string intermediateOutputDirectory, string sourceAssembly, ILogger logger, bool isBridgeBasedVersion, out string sgenCommandLineParameters, out string sgenCommandLineParametersContinued, out bool sgenIsContinued)
        {
            //-------------------------------------------------------------------------------
            // Create or clear the obj/Debug/TempSGen folder
            //-------------------------------------------------------------------------------
            string tempFolderForSerializationAssemblies = GetTempFolderForSerializationAssemblies(intermediateOutputDirectory);

            if (Directory.Exists(tempFolderForSerializationAssemblies))
            {
                foreach (string filePath in Directory.GetFiles(tempFolderForSerializationAssemblies))
                {
                    try
                    {
                        File.Delete(filePath);
                    }
                    catch (Exception ex)
                    {
                        logger.WriteError("Could not delete the following temporary file: " + filePath + "   - Please delete the file manually. If the error persists, please contact [email protected] - " + ex.Message);
                        sgenCommandLineParameters          = null;
                        sgenCommandLineParametersContinued = null;
                        sgenIsContinued = false;
                        return(false);
                    }
                }
            }
            else
            {
                Directory.CreateDirectory(tempFolderForSerializationAssemblies);
            }

            //-------------------------------------------------------------------------------
            // Find all the types for which we need to create the serialization assemblies:
            //-------------------------------------------------------------------------------

            string[] typesThatAreSerializable;

            // Create the "TypesResolver" on a separate AppDomain so that the types loaded for reflection can be unloaded when done.
            using (var reflectionOnSeparateAppDomain = new ReflectionOnSeparateAppDomainHandler())
            {
                string assemblySimpleName = reflectionOnSeparateAppDomain.LoadAssembly(sourceAssembly, loadReferencedAssembliesToo: false, isBridgeBasedVersion: isBridgeBasedVersion, isCoreAssembly: false, nameOfAssembliesThatDoNotContainUserCode: "");
                string commaSeparatedTypesThatAreSerializable = reflectionOnSeparateAppDomain.FindCommaSeparatedTypesThatAreSerializable(assemblySimpleName);
                typesThatAreSerializable = commaSeparatedTypesThatAreSerializable.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }

            //-------------------------------------------------------------------------------
            // Generate the command line call to the "sgen.exe" tool, that will generate the C# source code for the serialization assemblies:
            //-------------------------------------------------------------------------------

            if (typesThatAreSerializable.Length > 0)
            {
                StringBuilder commandLineBuilder          = new StringBuilder();
                StringBuilder commandLineBuilderContinued = new StringBuilder();

                string sourceAssemblyAbsolutePath = Path.Combine(Directory.GetCurrentDirectory(), sourceAssembly);

                string shortPathName = ShortPathHelper.GetShortPathName(sourceAssemblyAbsolutePath); // Note: we call "ShortPathHelper.GetShortPathName" so that we don't need to surround the path with double quotes (which don't work with the MSBuild Exec tasc):

                commandLineBuilder.Append(shortPathName);
                commandLineBuilderContinued.Append(shortPathName);

                commandLineBuilder.Append(" /keep"); // Note: "keep" will prevent sgen from deleting the ".cs" source file after generating the serialization assembly
                commandLineBuilderContinued.Append(" /keep");

                commandLineBuilder.Append(" /v"); // Note: "v" will display verbose output for debugging, and will list types from the target assembly that cannot be serialized with the XmlSerializer.
                commandLineBuilderContinued.Append(" /v");

                commandLineBuilder.Append(" /force"); // Note: "force" will force replace the generated assembly if it already exists.
                commandLineBuilderContinued.Append(" /force");

                int charactersCount = 0; // We count the characters because command lines are limited to 32,768 characters.
                sgenIsContinued = false;
                Dictionary <string, string> typesLocalNameToFullName = new Dictionary <string, string>();
                foreach (string serializableType in typesThatAreSerializable)
                {
                    // Verify that there are no 2 classes with the same local name (SGEN.exe does not support processing two classes with the same local name, unless they have some XML attribute to specify the namespace, but the current version of the XmlSerializer does not support such XML namespace attributes:
                    string serializableTypeLocalName = (serializableType.Contains('.') ? serializableType.Substring(serializableType.LastIndexOf('.') + 1) : serializableType);
                    if (typesLocalNameToFullName.ContainsKey(serializableTypeLocalName))
                    {
                        throw new Exception(@"The following serializable classes have the same name: """ + serializableType + @""" and """ + typesLocalNameToFullName[serializableTypeLocalName] + @""". The current version of C#/XAML for HTML5 does not allow serializing two classes that have the same name. This is due to the fact that the XmlSerializer does not support namespaces at the moment. To work around this limitation, please rename one of the two classes, or remove its [Serializable] or [DataContract] attribute.");
                    }
                    else
                    {
                        typesLocalNameToFullName.Add(serializableTypeLocalName, serializableType);
                    }

                    // Build the command line parameter related to the list of types that are serializable:
                    string fragment = " /type:" + serializableType; // Note: the full type name (ie. namespace + name) is required.

                    if (!sgenIsContinued)                           // This is due to the fact that command lines are limited to 32,768 characters, so we split into two calls if necessary.
                    {
                        commandLineBuilder.Append(fragment);
                    }
                    else
                    {
                        commandLineBuilderContinued.Append(fragment);
                    }

                    charactersCount += fragment.Length;
                    if (charactersCount > 32000)
                    {
                        sgenIsContinued = true;
                    }
                    if (charactersCount > 64000)
                    {
                        throw new Exception("The maximum length of the SGEN command line has been exceeded (64,000 characters). Please reduce the number of serializable types and try again.");
                    }
                }

                string outParam = @" /out:" + ShortPathHelper.GetShortPathName(tempFolderForSerializationAssemblies); // Note: we call "ShortPathHelper.GetShortPathName" so that we don't need to surround the path with double quotes (which don't work with the MSBuild Exec tasc):
                commandLineBuilder.Append(outParam);
                commandLineBuilderContinued.Append(outParam);


                sgenCommandLineParameters = commandLineBuilder.ToString();

                if (sgenIsContinued)
                {
                    sgenCommandLineParametersContinued = commandLineBuilderContinued.ToString();
                }
                else
                {
                    sgenCommandLineParametersContinued = string.Empty;
                }


                // Fix the 8192 characters length limitation (for more information, read the comments in the method "Fix8192charactersIssue"):
                sgenCommandLineParameters          = Fix8192charactersIssue(sgenCommandLineParameters);
                sgenCommandLineParametersContinued = Fix8192charactersIssue(sgenCommandLineParametersContinued);
            }
            else
            {
                sgenCommandLineParameters          = string.Empty;
                sgenCommandLineParametersContinued = string.Empty;
                sgenIsContinued = false;
            }

            logger.WriteMessage("SGEN command line parameters: " + sgenCommandLineParameters, Microsoft.Build.Framework.MessageImportance.Low);
            return(true);
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            try
            {
                // Find token in default location
                string requestToken  = null;
                string authorization = Request.Headers.Get("Authorization");
                if (!string.IsNullOrEmpty(authorization))
                {
                    if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        requestToken = authorization.Substring("Bearer ".Length).Trim();
                    }
                }

                // Give application opportunity to find from a different location, adjust, or reject token
                var requestTokenContext = new OAuthRequestTokenContext(Context, requestToken);
                await Options.Provider.RequestToken(requestTokenContext);

                // If no token found, no further work possible
                if (string.IsNullOrEmpty(requestTokenContext.Token))
                {
                    return(null);
                }

                // Call provider to process the token into data
                var tokenReceiveContext = new AuthenticationTokenReceiveContext(
                    Context,
                    Options.AccessTokenFormat,
                    requestTokenContext.Token);

                await Options.AccessTokenProvider.ReceiveAsync(tokenReceiveContext);

                if (tokenReceiveContext.Ticket == null)
                {
                    tokenReceiveContext.DeserializeTicket(tokenReceiveContext.Token);
                }

                AuthenticationTicket ticket = tokenReceiveContext.Ticket;
                if (ticket == null)
                {
                    _logger.WriteWarning("invalid bearer token received");
                    return(null);
                }

                // Validate expiration time if present
                DateTimeOffset currentUtc = Options.SystemClock.UtcNow;

                if (ticket.Properties.ExpiresUtc.HasValue &&
                    ticket.Properties.ExpiresUtc.Value < currentUtc)
                {
                    _logger.WriteWarning("expired bearer token received");
                    return(null);
                }

                // Give application final opportunity to override results
                var context = new OAuthValidateIdentityContext(Context, Options, ticket);
                if (ticket != null &&
                    ticket.Identity != null &&
                    ticket.Identity.IsAuthenticated)
                {
                    // bearer token with identity starts validated
                    context.Validated();
                }
                if (Options.Provider != null)
                {
                    await Options.Provider.ValidateIdentity(context);
                }
                if (!context.IsValidated)
                {
                    return(null);
                }

                // resulting identity values go back to caller
                return(context.Ticket);
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(null);
            }
        }
        private ExecuteResult ExecuteImpl(Process process, string exeName, Benchmark benchmark, ILogger logger, IDiagnoser compositeDiagnoser = null)
        {
            process.PriorityClass = ProcessPriorityClass.High;
            if (!benchmark.Job.Affinity.IsAuto)
                process.ProcessorAffinity = new IntPtr(benchmark.Job.Affinity.Value);

            var lines = new List<string>();
            string line;
            while ((line = process.StandardOutput.ReadLine()) != null)
            {
                logger?.WriteLine(line);
                if (!line.StartsWith("//") && !string.IsNullOrEmpty(line))
                    lines.Add(line);

                if (compositeDiagnoser == null)
                    continue;

                // This is important so the Diagnoser can know the [Benchmark] methods will have run and (e.g.) it can do a Memory Dump
                if (diagnosticsAlreadyRun == false && line.StartsWith(IterationMode.MainWarmup.ToString()))
                {
                    try
                    {
                        compositeDiagnoser.AfterBenchmarkHasRun(benchmark, process);
                    }
                    finally
                    {
                        // Always set this, even if something went wrong, otherwise we will try on every run of a benchmark batch
                        diagnosticsAlreadyRun = true;
                    }
                }
            }

            if (process.HasExited && process.ExitCode != 0)
            {
                if (logger != null)
                {
                    logger.WriteError(
                        $"Something bad happened during the execution of {exeName}. Try to run the benchmark again using an AnyCPU application\n");
                }
                else
                {
                    if (exeName.ToLowerInvariant() == "msbuild")
                        Console.WriteLine("Build failed");
                }
                return new ExecuteResult(true, new string[0]);
            }

            return new ExecuteResult(true, lines);
        }
Exemple #20
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;
            string code  = null;
            string state = null;

            try
            {
                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);

                if (code == null)
                {
                    // Null if the remote server returns an error.
                    return(new AuthenticationTicket(null, properties));
                }

                var tokenRequestParameters = string.Format(
                    CultureInfo.InvariantCulture,
                    "client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code",
                    Uri.EscapeDataString(Options.ClientId),
                    Uri.EscapeDataString(GenerateRedirectUri(properties)),
                    Uri.EscapeDataString(Options.ClientSecret),
                    code);

                var body = new Dictionary <string, string> {
                    { "client_id", Options.ClientId },
                    { "redirect_uri", GenerateRedirectUri(properties) },
                    { "client_secret", Options.ClientSecret },
                    { "code", Uri.EscapeDataString(code) },
                    { "grant_type", "authorization_code" }
                };

                HttpResponseMessage tokenResponse = await _httpClient.PostAsync(string.Format(TokenEndpoint, Options.Domain), new FormUrlEncodedContent(body), Request.CallCancelled);
                await EnsureTokenExchangeSuccessful(tokenResponse);

                string text = await tokenResponse.Content.ReadAsStringAsync();

                JObject tokens = JObject.Parse(text);

                string accessToken  = tokens["access_token"].Value <string>();
                string idToken      = tokens["id_token"] != null ? tokens["id_token"].Value <string>() : null;
                string refreshToken = tokens["refresh_token"] != null ? tokens["refresh_token"].Value <string>() : null;

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(
                    string.Format(UserInfoEndpoint, Options.Domain) + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                var context = new Auth0AuthenticatedContext(Context, user, accessToken, idToken, refreshToken);
                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, ClaimValueTypes.String, context.Connection),
                    new Claim("user_id", context.Id, ClaimValueTypes.String, Constants.Auth0Issuer),

                    new Claim(ClaimTypes.Name, context.Name, ClaimValueTypes.String, context.Connection),
                    new Claim("name", context.Name, ClaimValueTypes.String, context.Connection),
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, ClaimValueTypes.String, context.Connection));
                    context.Identity.AddClaim(new Claim("email", context.Email, ClaimValueTypes.String, context.Connection));
                }

                if (!string.IsNullOrWhiteSpace(context.Nickname))
                {
                    context.Identity.AddClaim(new Claim("nickname", context.Nickname, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.FirstName))
                {
                    context.Identity.AddClaim(new Claim("given_name", context.FirstName, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.LastName))
                {
                    context.Identity.AddClaim(new Claim("family_name", context.LastName, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Connection))
                {
                    context.Identity.AddClaim(new Claim("connection", context.Connection, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Picture))
                {
                    context.Identity.AddClaim(new Claim("picture", context.Picture, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Provider))
                {
                    context.Identity.AddClaim(new Claim("provider", context.Provider, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.ProviderAccessToken))
                {
                    context.Identity.AddClaim(new Claim("provider_access_token", context.ProviderAccessToken, ClaimValueTypes.String, context.Connection));
                }

                if (Options.SaveIdToken && !string.IsNullOrWhiteSpace(context.IdToken))
                {
                    context.Identity.AddClaim(new Claim("id_token", context.IdToken, ClaimValueTypes.String, Constants.Auth0Issuer));
                }
                if (Options.SaveRefreshToken && !string.IsNullOrWhiteSpace(context.RefreshToken))
                {
                    context.Identity.AddClaim(new Claim("refresh_token", context.RefreshToken, ClaimValueTypes.String, Constants.Auth0Issuer));
                }

                context.Identity.AddClaim(new Claim("access_token", context.AccessToken, ClaimValueTypes.String, Constants.Auth0Issuer));

                context.Properties = properties ?? new AuthenticationProperties();

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                var tokenExchangeFailedContext = new Auth0TokenExchangeFailedContext(
                    Context, Options,
                    ex, code, state);
                Options.Provider.TokenExchangeFailed(tokenExchangeFailedContext);

                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Exemple #21
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            try
            {
                base.OnModelCreating(modelBuilder);

                modelBuilder.Conventions.Remove <ManyToManyCascadeDeleteConvention>();
                modelBuilder.Conventions.Remove <OneToManyCascadeDeleteConvention>();

                #region [ External UDS ]
                AppDomain myDomain = Thread.GetDomain();
                if (File.Exists(UDSAssemblyFileName))
                {
                    Assembly udsExternalAssembly = myDomain.GetAssemblies().SingleOrDefault(f => f.FullName == UDSAssemblyFullName);
                    if (udsExternalAssembly == null)
                    {
                        udsExternalAssembly = Assembly.LoadFile(UDSAssemblyFileName);
                    }
                    modelBuilder.Configurations.AddFromAssembly(udsExternalAssembly);
                    foreach (Type t in udsExternalAssembly.DefinedTypes.Where(f => f.IsDefined(typeof(TableAttribute), false)))
                    {
                        modelBuilder.RegisterEntityType(t);
                    }
                }
                #endregion

                #region [ Collaborations ]
                modelBuilder.Configurations
                .Add(new CollaborationLogMap())
                .Add(new CollaborationMap())
                .Add(new CollaborationAggregateMap())
                .Add(new CollaborationVersioningMap())
                .Add(new CollaborationSignMap())
                .Add(new CollaborationUserMap());

                #endregion

                #region [ Templates ]
                modelBuilder.Configurations
                .Add(new TemplateCollaborationMap())
                .Add(new TemplateCollaborationDocumentRepositoryMap())
                .Add(new TemplateCollaborationUserMap())
                .Add(new TemplateReportMap());
                #endregion

                #region [ Commons ]

                modelBuilder.Configurations
                .Add(new LocationMap())
                .Add(new RoleMap())
                .Add(new CategoryMap())
                .Add(new ContactMap())
                .Add(new ContactPlaceNameMap())
                .Add(new ContactTitleMap())
                .Add(new SecurityGroupMap())
                .Add(new SecurityUserMap())
                .Add(new ContainerMap())
                .Add(new ContainerGroupMap())
                .Add(new ContainerPropertyMap())
                .Add(new RoleGroupMap())
                .Add(new RoleUserMap())
                .Add(new CategoryFascicleMap())
                .Add(new CategoryFascicleRightMap())
                .Add(new IncrementalMap())
                .Add(new CategorySchemaMap())
                .Add(new TableLogMap())
                .Add(new MetadataRepositoryMap())
                .Add(new ParameterEnvMap())
                .Add(new PrivacyLevelMap())
                .Add(new UserLogMap())
                .Add(new MetadataValueMap())
                .Add(new MetadataValueContactMap());
                #endregion

                #region [ Dossiers ]
                modelBuilder.Configurations
                .Add(new DossierMap())
                .Add(new DossierLogMap())
                .Add(new DossierDocumentMap())
                .Add(new DossierRoleMap())
                .Add(new DossierCommentMap())
                .Add(new DossierFolderMap())
                .Add(new DossierFolderRoleMap())
                .Add(new DossierLinkMap());
                #endregion

                #region [ Desks ]
                modelBuilder.Configurations
                .Add(new DeskCollaborationMap())
                .Add(new DeskDocumentEndorsementMap())
                .Add(new DeskDocumentMap())
                .Add(new DeskDocumentVersionMap())
                .Add(new DeskLogMap())
                .Add(new DeskMap())
                .Add(new DeskMessageMap())
                .Add(new DeskRoleUsersMap())
                .Add(new DeskStoryBoardMap());
                #endregion

                #region [ DocumentArchives ]
                modelBuilder.Configurations
                .Add(new DocumentSeriesMap())
                .Add(new DocumentSeriesItemMap())
                .Add(new DocumentSeriesItemRoleMap())
                .Add(new DocumentSeriesItemLogMap())
                .Add(new DocumentSeriesConstraintMap())
                .Add(new DocumentSeriesItemLinkMap());
                #endregion

                #region [ DocumentUnits ]
                modelBuilder.Configurations
                .Add(new DocumentUnitMap())
                .Add(new DocumentUnitRoleMap())
                .Add(new DocumentUnitChainMap())
                .Add(new DocumentUnitFascicleHistoricizedCategoryMap())
                .Add(new DocumentUnitFascicleCategoryMap())
                .Add(new DocumentUnitUserMap());
                #endregion

                #region [ Fascicles ]
                modelBuilder.Configurations
                .Add(new FascicleMap())
                .Add(new FasciclePeriodMap())
                .Add(new FascicleLogMap())
                .Add(new FascicleLinkMap())
                .Add(new FascicleDocumentMap())
                .Add(new FascicleRoleMap())
                .Add(new FascicleFolderMap())
                .Add(new FascicleDocumentUnitMap());
                #endregion

                #region [ Messages ]
                modelBuilder.Configurations
                .Add(new MessageAttachmentMap())
                .Add(new MessageContactEmailMap())
                .Add(new MessageContactMap())
                .Add(new MessageEmailMap())
                .Add(new MessageLogMap())
                .Add(new MessageMap());
                #endregion

                #region [ OCharts ]
                modelBuilder.Configurations
                .Add(new OChartMap())
                .Add(new OChartItemMap())
                .Add(new OChartItemContainerMap());
                #endregion

                #region [ PECMails ]
                modelBuilder.Configurations
                .Add(new PECMailMap())
                .Add(new PECMailBoxMap())
                .Add(new PECMailLogMap())
                .Add(new PECMailReceiptMap())
                .Add(new PECMailAttachmentMap())
                .Add(new PECMailBoxConfigurationMap());
                #endregion

                #region [ Protocols ]
                modelBuilder.Configurations
                .Add(new ProtocolTypeMap())
                .Add(new ProtocolMap())
                .Add(new ProtocolRoleMap())
                .Add(new ProtocolRoleUserMap())
                .Add(new ProtocolLogMap())
                .Add(new ProtocolContactMap())
                .Add(new ProtocolParerMap())
                .Add(new ProtocolLinkMap())
                .Add(new ProtocolDocumentTypeMap())
                .Add(new ProtocolUserMap())
                .Add(new ProtocolContactManualMap())
                .Add(new ProtocolDraftMap())
                .Add(new AdvancedProtocolMap());;

                #endregion

                #region [ TemplateDocumentRepositories ]
                modelBuilder.Configurations
                .Add(new TemplateDocumentRepositoryMap());
                #endregion

                #region [ Resolutions ]
                modelBuilder.Configurations
                .Add(new ResolutionMap())
                .Add(new ResolutionRoleMap())
                .Add(new ResolutionContactMap())
                .Add(new FileResolutionMap())
                .Add(new ResolutionKindMap())
                .Add(new ResolutionKindDocumentSeriesMap())
                .Add(new ResolutionDocumentSeriesItemMap())
                .Add(new ResolutionLogMap());
                #endregion

                #region [ Workflow ]
                modelBuilder.Configurations
                .Add(new WorkflowActivityMap())
                .Add(new WorkflowActivityLogMap())
                .Add(new WorkflowInstanceMap())
                .Add(new WorkflowPropertyMap())
                .Add(new WorkflowRepositoryMap())
                .Add(new WorkflowAuthorizationMap())
                .Add(new WorkflowRoleMappingMap())
                .Add(new WorkflowInstanceLogMap())
                .Add(new WorkflowInstanceRoleMap())
                .Add(new WorkflowEvaluationPropertyMap());
                #endregion

                #region [ UDS ]

                modelBuilder.Configurations
                .Add(new UDSRepositoryMap())
                .Add(new UDSSchemaRepositoryMap())
                .Add(new UDSTypologyMap())
                .Add(new UDSLogMap())
                .Add(new UDSRoleMap())
                .Add(new UDSUserMap())
                .Add(new UDSContactMap())
                .Add(new UDSMessageMap())
                .Add(new UDSDocumentUnitMap())
                .Add(new UDSPECMailMap())
                .Add(new UDSCollaborationMap());
                #endregion

                #region [ MassimariScarto ]
                modelBuilder.Configurations
                .Add(new MassimarioScartoMap());
                #endregion

                #region [ Conservation ]
                modelBuilder.Configurations
                .Add(new ConservationMap());
                #endregion

                #region [ Monitors ]
                modelBuilder.Configurations
                .Add(new TransparentAdministrationMonitorLogMap());
                #endregion

                #region [ Parameter ]
                modelBuilder.Configurations
                .Add(new ParameterMap());
                #endregion

                #region [ PosteOnLine ]
                modelBuilder.Configurations
                .Add(new PosteOnLineRequestMap())
                .Add(new LOLRequestMap())
                .Add(new TOLRequestMap())
                .Add(new ROLRequestMap())
                .Add(new SOLRequestMap());

                #endregion

                #region [ JeepServiceHosts ]
                modelBuilder.Configurations
                .Add(new JeepServiceHostMap());
                #endregion

                #region [ Tenants ]
                modelBuilder.Configurations
                .Add(new TenantMap())
                .Add(new TenantConfigurationMap())
                .Add(new TenantWorkflowRepositoryMap())
                .Add(new TenantAOOMap());
                #endregion

                #region [ Processes ]

                modelBuilder.Configurations
                .Add(new ProcessMap())
                .Add(new ProcessFascicleTemplateMap())
                .Add(new ProcessFascicleWorkflowRepositoryMap());

                #endregion

                #region [ Tasks ]
                modelBuilder.Configurations
                .Add(new TaskHeaderMap())
                .Add(new TaskHeaderProtocolMap());
                #endregion
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex, LogCategories);
                throw new DSWException(string.Concat("DSW DataContext - unexpected exception was thrown while invoking OnModelCreating: ", ex.Message), ex, DSWExceptionCode.DB_ModelMappingError);
            }
        }
Exemple #22
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("client_id", Options.ClientId));
                body.Add(new KeyValuePair <string, string>("client_secret", Options.ClientSecret));

                // Request the token
                HttpResponseMessage tokenResponse =
                    await _httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                dynamic form = JObject.Parse(text);

                string accessToken = form.access_token;

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                // Get the Google user
                HttpResponseMessage graphResponse = await _httpClient.GetAsync(
                    UserInfoEndpoint + Uri.EscapeDataString(accessToken), Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                var context = new GlassAuthenticatedContext(Context, user, accessToken)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };

                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim("urn:Glass:fullName", context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;
                string msg   = null;

                // 获取code,多个值的情况下取第一个,没有值的情况下返回null
                var values = Request.Query.GetValues(nameof(code));
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }

                values = Request.Query.GetValues("msg");
                if (values != null && values.Count == 1)
                {
                    msg = values[0];
                }

                values = Request.Query.GetValues(nameof(state));
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                if (String.IsNullOrWhiteSpace(code))
                {
                    logger.WriteWarning("Invalid return {0}", msg);
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                string tokenRequest = Options.TokenEndpoint +
                                      "?&grant_type=authorization_code" +
                                      "&client_id=" + Uri.EscapeDataString(Options.AppId) +
                                      "&client_secret=" + Uri.EscapeDataString(Options.AppKey) +
                                      "&code=" + Uri.EscapeDataString(code) +
                                      "&redirect_uri=" + Uri.EscapeDataString(redirectUri);

                var response = await httpClient.GetAsync(tokenRequest, Request.CallCancelled);

                response.EnsureSuccessStatusCode();

                var queryString = await response.Content.ReadAsStringAsync();

                // 解析返回的查询字符串查询字符串
                // access_token=FE04************************CCE2&expires_in=7776000
                var nameValueCollection = HttpUtility.ParseQueryString("?" + queryString);

                string accessToken  = nameValueCollection.Get("access_token");  // 授权令牌
                string expires      = nameValueCollection.Get("expires_in");    // 过期时间
                string refreshToken = nameValueCollection.Get("refresh_token"); // 刷新令牌


                var openIdEndpoint = Options.OptionIdEndpoint + "?access_token=" +
                                     Uri.EscapeDataString(accessToken);

                var openIdresponse = await httpClient.GetAsync(openIdEndpoint, Request.CallCancelled);

                openIdresponse.EnsureSuccessStatusCode();

                // 返回值 callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
                var text = await openIdresponse.Content.ReadAsStringAsync();

                text = text.Substring(text.IndexOf('{'), text.LastIndexOf('}') - text.IndexOf('{') + 1);
                var jsonObject = JObject.Parse(text);
                var openId     = jsonObject.Value <string>("openid");

                var userInformationEndpoint = Options.UserInformationEndpoint +
                                              "?access_token=" + Uri.EscapeDataString(accessToken) +
                                              "&oauth_consumer_key=" + Uri.EscapeDataString(Options.AppId) +
                                              "&openid=" + Uri.EscapeDataString(openId);

                // 请求用户信息
                var userInformationResponse = await httpClient.GetAsync(userInformationEndpoint, Request.CallCancelled);

                userInformationResponse.EnsureSuccessStatusCode();

                var userJson = await userInformationResponse.Content.ReadAsStringAsync();

                jsonObject = JObject.Parse(userJson);

                var context = new TencentAuthenticatedContext(Context, jsonObject, accessToken, refreshToken, expires,
                                                              openId)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };

                if (!string.IsNullOrEmpty(context.OpenId))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.OpenId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.NickName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.NickName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Gender))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Gender, context.Gender, XmlSchemaString, Options.AuthenticationType));
                }
                context.Identity.AddClaim(new Claim("urn:tencentaccount:id", context.OpenId, XmlSchemaString, Options.AuthenticationType));
                context.Identity.AddClaim(new Claim("urn:tencentaccount:nickname", context.NickName, XmlSchemaString,
                                                    Options.AuthenticationType));

                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #24
0
        /// <summary>
        /// Suppression physique de fichiers dans un projet Visual Studio.
        /// Cette méthode est appelée soit :
        /// - Par le rollback d'une transaction pour supprimer
        /// les fichiers qui n'ont pas été regénérés (au cas ou la stratégie à changer et
        /// génére moins de fichier) (force=false)
        /// - Lors de la suppression d'une stratégie quand on veut supprimer les fichiers
        /// que cette stratégie avait généré. (force=true)
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="items">Liste des items à supprimer</param>
        /// <param name="force">if set to <c>true</c> [force].</param>
        internal void DeleteFiles(Project project, List <MapItem> items, bool force)
        {
            ILogger logger = ServiceLocator.Instance.GetService <ILogger>();

            // Liste des répertoires qui ont eu des fichiers supprimés pour pouvoir
            //  les supprimer ensuite
            List <string> folders = new List <string>();

            if (items.Count > 0)
            {
                foreach (MapItem item in items)
                {
                    // Suppression des fichiers
                    try
                    {
                        // Si ce fichier n'existe pas dans le fichier de mapping, c'est
                        // qu'il n'a pas été regénéré donc on supprime physiquement le
                        // fichier le concernant.
                        if (force || FindMapItem(item.FileName) == null)
                        {
                            FileInfo file = new FileInfo(ResolvePath(item.FileName));
                            // Oui on supprime dans l'arborescence du projet et sur le disque
                            Project prj = project;
                            if (prj == null)
                            {
                                prj = ServiceLocator.Instance.ShellHelper.FindProjectByName(item.ProjectName);
                            }
                            ProjectItem pi = null;
                            if (project.ProjectItems != null)
                            {
                                pi =
                                    ServiceLocator.Instance.ShellHelper.FindProjectItemByFileName(prj.ProjectItems,
                                                                                                  file.FullName);
                            }

                            if (pi != null)
                            {
                                // Suppression dans le projet
                                pi.Delete();
                            }

                            // Suppression physique
                            Utils.DeleteFile(file.FullName);

                            // Sauvegarde du répertoire
                            string folderName = Path.GetDirectoryName(file.FullName);
                            if (!folders.Contains(folderName))
                            {
                                folders.Add(folderName);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (logger != null)
                        {
                            logger.WriteError("Mapper", "Purge generated file before generation", ex);
                        }
                    }
                }

                // Sauvegarde du fichier de mapping
                //Save();

                // Suppression des répertoires
                // Tri dans l'ordre inverse des répertoires pour pouvoir supprimer
                // en commencant par les dossiers enfants et en redescendant vers le père
                folders.Sort(delegate(string a, string b) { return(b.CompareTo(a)); });

                foreach (string folder in folders)
                {
                    DirectoryInfo di = new DirectoryInfo(folder);
                    if (!di.Exists || di.GetFiles().Length > 0 || di.GetDirectories().Length > 0)
                    {
                        continue;
                    }

                    if (project.ProjectItems != null)
                    {
                        ProjectItem pi =
                            ServiceLocator.Instance.ShellHelper.FindProjectItemByFileName(project.ProjectItems, folder);
                        if (pi != null)
                        {
                            pi.Delete();
                        }
                    }
                    // Suppression physique
                    Utils.RemoveDirectory(folder);
                }
            }
        }
Exemple #25
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            _logger.WriteVerbose("AuthenticateCore");

            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                var query  = Request.Query;
                var values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }

                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                string tokenEndpoint = "https://oauth.vk.com/access_token";

                string requestPrefix = Request.GetRealRequestScheme() + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.ReturnEndpointPath;

                string tokenRequest =
                    "?client_id=" + Uri.EscapeDataString(Options.AppId) +
                    "&client_secret=" + Uri.EscapeDataString(Options.AppSecret) +
                    "&code=" + Uri.EscapeDataString(code) +
                    "&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
                    "&v=" + vkApiVersion;

                HttpResponseMessage tokenResponse = await _httpClient.GetAsync(tokenEndpoint + tokenRequest, Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                var form = JsonConvert.DeserializeObject <Dictionary <string, object> >(text);

                var accessToken = (string)form["access_token"];
                var userId      = (long)form["user_id"];

                string graphApiEndpoint = "https://api.vk.com/method/users.get" +
                                          "?user_id=" + userId +
                                          "&fields=sex,photo_100,screen_name" +
                                          "&name_case=Nom" +
                                          "&access_token=" + Uri.EscapeDataString(accessToken) +
                                          "&v=" + vkApiVersion;

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(graphApiEndpoint, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject data = JObject.Parse(text);
                var     user = (JObject)data["response"].First;

                var context = new VkAuthenticatedContext(Context, user, accessToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString,
                                                        Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString,
                                                        Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.FirstName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.GivenName, context.FirstName));
                }
                if (!string.IsNullOrEmpty(context.LastName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Surname, context.LastName));
                }
                if (!string.IsNullOrEmpty(context.AvatarUrl))
                {
                    context.Identity.AddClaim(new Claim("AvatarUrl", context.AvatarUrl));
                }
                context.Identity.AddClaim(new Claim(ClaimTypes.Gender, context.Sex.ToString()));
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }

            return(new AuthenticationTicket(null, properties));
        }
Exemple #26
0
        public async Task <ExitCode> ExecuteAsync(
            ILogger logger,
            IReadOnlyCollection <IVariable> buildVariables,
            CancellationToken cancellationToken)
        {
            var app = new CastaneaApplication();

            PathLookupSpecification pathLookupSpecification = DefaultPaths.DefaultPathLookupSpecification;

            string vcsRoot       = buildVariables.Require(WellKnownVariables.SourceRoot).ThrowIfEmptyValue().Value;
            string nuGetExetPath = buildVariables.Require(WellKnownVariables.ExternalTools_NuGet_ExePath)
                                   .ThrowIfEmptyValue()
                                   .Value;

            var rootDirectory = new DirectoryInfo(vcsRoot);

            int listFilesAttempt = 1;

            int listFilesMaxAttempts = 5;

            bool listFilesSucceeded = false;

            IReadOnlyCollection <string>   packagesConfigFiles = new List <string>();
            IReadOnlyCollection <FileInfo> solutionFiles       = new List <FileInfo>();

            while (listFilesAttempt <= listFilesMaxAttempts && !listFilesSucceeded)
            {
                try
                {
                    rootDirectory.Refresh();

                    packagesConfigFiles =
                        rootDirectory.EnumerateFiles("packages.config", SearchOption.AllDirectories)
                        .Where(file => !pathLookupSpecification.IsFileBlackListed(file.FullName, vcsRoot).Item1)
                        .Select(file => file.FullName)
                        .ToReadOnlyCollection();

                    rootDirectory.Refresh();

                    solutionFiles =
                        rootDirectory.EnumerateFiles("*.sln", SearchOption.AllDirectories)
                        .Where(file => !pathLookupSpecification.IsFileBlackListed(file.FullName, vcsRoot).Item1)
                        .ToReadOnlyCollection();

                    listFilesSucceeded = true;
                }
                catch (Exception ex)
                {
                    if (listFilesAttempt == listFilesMaxAttempts)
                    {
                        logger.WriteError($"Could not enumerable packages.config files or solutions files. {ex}");
                        return(ExitCode.Failure);
                    }

                    logger.WriteWarning(
                        $"Attempt {listFilesAttempt} of {listFilesMaxAttempts} failed, retrying. {ex}");
                    listFilesAttempt++;
                }
            }

            if (!packagesConfigFiles.Any())
            {
                logger.WriteWarning("Could not find any packages.config files, skipping package restore");
                return(ExitCode.Success);
            }

            if (!solutionFiles.Any())
            {
                logger.WriteError("Could not find any solution file, cannot determine package output directory");
                return(ExitCode.Failure);
            }

            if (solutionFiles.Count > 1)
            {
                logger.WriteError("Found more than one solution file, cannot determine package output directory");
                return(ExitCode.Failure);
            }

            FileInfo solutionFile = solutionFiles.Single();

            string allFiles = string.Join(Environment.NewLine, packagesConfigFiles);

            try
            {
// ReSharper disable once PossibleNullReferenceException
                string outputDirectoryPath = Path.Combine(solutionFile.Directory.FullName, "packages");

                new DirectoryInfo(outputDirectoryPath).EnsureExists();

                bool disableParallelProcessing =
                    buildVariables.GetBooleanByKey(
                        WellKnownVariables.NuGetRestoreDisableParallelProcessing,
                        false);

                bool noCache = buildVariables.GetBooleanByKey(
                    WellKnownVariables.NuGetRestoreNoCache,
                    false);

                var nuGetConfig = new NuGetConfig
                {
                    NuGetExePath              = nuGetExetPath,
                    OutputDirectory           = outputDirectoryPath,
                    DisableParallelProcessing = disableParallelProcessing,
                    NoCache = noCache
                };

                nuGetConfig.PackageConfigFiles.AddRange(packagesConfigFiles);

                Action <string> debugAction = null;

                string prefix = typeof(CastaneaApplication).Namespace;

                if (logger.LogLevel.IsLogging(LogLevel.Verbose))
                {
                    debugAction = message => logger.WriteVerbose(message, prefix);
                }

                int restoredPackages = 0;

                int attempt = 1;

                int maxAttempts = 5;

                bool succeeded = false;

                while (attempt <= maxAttempts && !succeeded)
                {
                    try
                    {
                        restoredPackages = app.RestoreAllSolutionPackages(
                            nuGetConfig,
                            message => logger.Write(message, prefix),
                            message => logger.WriteError(message, prefix),
                            debugAction);

                        if (restoredPackages == 0)
                        {
                            logger.WriteWarning($"No packages was restored as defined in {allFiles}");
                            return(ExitCode.Success);
                        }

                        succeeded = true;
                    }
                    catch (Exception ex)
                    {
                        if (attempt < maxAttempts)
                        {
                            logger.WriteWarning(
                                $"Attempt {attempt} of {maxAttempts}: could not restore NuGet packages, trying againg. {ex.Message}");
                        }
                        else
                        {
                            logger.WriteError($"Could not restore NuGet packages.{ex}");
                            return(ExitCode.Failure);
                        }

                        attempt++;
                    }
                }

                logger.Write($"Restored {restoredPackages} package configurations defined in {allFiles}");
            }
            catch (Exception ex)
            {
                logger.WriteError($"Could not restore packages defined in '{allFiles}'. {ex}");
                return(ExitCode.Failure);
            }

            try
            {
                foreach (FileInfo fileInfo in solutionFiles)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    string packagesDirectory = Path.Combine(fileInfo.Directory.FullName, "packages");

                    if (Directory.Exists(packagesDirectory))
                    {
                        foreach (INuGetPackageRestoreFix nuGetPackageRestoreFix in _fixes)
                        {
                            await nuGetPackageRestoreFix.FixAsync(packagesDirectory, logger);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ExceptionExtensions.IsFatal(ex))
                {
                    throw;
                }

                logger.WriteWarning(ex.ToString());
            }

            return(ExitCode.Success);
        }
Exemple #27
0
        public static bool Execute(bool isSecondPass, string flagsString, string referencePathsString, string sourceAssemblyForPass2, string nameOfAssembliesThatDoNotContainUserCode, bool isBridgeBasedVersion, bool isProcessingCSHTML5Itself, ILogger logger, string typeForwardingAssemblyPath)
#endif

        {
            string passNumber    = (isSecondPass ? "2" : "1");
            string operationName = string.Format("C#/XAML for HTML5: BeforeXamlPreprocessor (pass {0})", passNumber);

            try
            {
                using (var executionTimeMeasuring = new ExecutionTimeMeasuring())
                {
                    //------- DISPLAY THE PROGRESS -------
                    logger.WriteMessage(operationName + " started.");

                    //-----------------------------------------------------
                    // Note: we create a static instance of the "ReflectionOnSeparateAppDomainHandler" to avoid reloading the assemblies for each XAML file.
                    // We dispose the static instance in the "AfterXamlPreprocessor" task.
                    //-----------------------------------------------------

                    if (isSecondPass && string.IsNullOrEmpty(sourceAssemblyForPass2))
                    {
                        throw new Exception(operationName + " failed because the SourceAssembly parameter was not specified during the second pass.");
                    }

                    // Create a new static instance of the "ReflectionOnSeparateAppDomainHandler":
                    ReflectionOnSeparateAppDomainHandler.Current = new ReflectionOnSeparateAppDomainHandler(typeForwardingAssemblyPath);
                    ReflectionOnSeparateAppDomainHandler reflectionOnSeparateAppDomain = ReflectionOnSeparateAppDomainHandler.Current;

#if BRIDGE
                    //todo: if we are compiling CSHTML5 itself (or CSHTML5.Stubs), we need to process the XAML files in CSHTML5,
                    // and for that we need to load the XAML types, so we need to load the previous version of CSHTML5 (from
                    // the NuGet package). Note: this is not supposed to lead to a circular reference because it is only used
                    // for the XamlPreprocessor to generate the .xaml.g.cs files from the .xaml files.
                    // To do so, we need to stop skipping the processing of the CSHTML5 and CSHTML5.Stubs assemblies (c.f.
                    // "Skip the assembly if it is not a user assembly" in "LoadAndProcessReferencedAssemblies").
#endif
                    // we load the source assembly early in case we are processing the CSHTML5.
                    if (isSecondPass && isProcessingCSHTML5Itself)
                    {
                        reflectionOnSeparateAppDomain.LoadAssembly(sourceAssemblyForPass2, loadReferencedAssembliesToo: true, isBridgeBasedVersion: isBridgeBasedVersion, isCoreAssembly: false, nameOfAssembliesThatDoNotContainUserCode: nameOfAssembliesThatDoNotContainUserCode);
                    }
#if CSHTML5BLAZOR
                    // work-around: reference path string is not correctly setted so we set it manually
                    string referencePathsString = OpenSilverHelper.ReferencePathsString(resolvedReferences);
#endif
                    // Retrieve paths of referenced .dlls and load them:
                    HashSet <string> referencePaths = (referencePathsString != null) ? new HashSet <string>(referencePathsString.Split(';')) : new HashSet <string>();

                    referencePaths.RemoveWhere(s => !s.ToLower().EndsWith(".dll") || s.Contains("DotNetBrowser") || s.ToLower().EndsWith(@"\bridge.dll"));

                    foreach (string referencedAssembly in AssembliesLoadHelper.EnsureCoreAssemblyIsFirstInList(referencePaths)) // Note: we ensure that the Core assembly is loaded first so that types such as "XmlnsDefinitionAttribute" are known when loading the other assemblies.
                    {
                        reflectionOnSeparateAppDomain.LoadAssembly(referencedAssembly, loadReferencedAssembliesToo: false, isBridgeBasedVersion: isBridgeBasedVersion, isCoreAssembly: false, nameOfAssembliesThatDoNotContainUserCode: nameOfAssembliesThatDoNotContainUserCode);
                    }

                    // Load "mscorlib.dll" too (this is useful for resolving Mscorlib types in XAML, such as <system:String x:Key="TestString" xmlns:system="clr-namespace:System;assembly=mscorlib">Test</system:String>)
                    reflectionOnSeparateAppDomain.LoadAssemblyMscorlib(isBridgeBasedVersion: isBridgeBasedVersion, isCoreAssembly: false, nameOfAssembliesThatDoNotContainUserCode: nameOfAssembliesThatDoNotContainUserCode);

                    // Load for reflection the source assembly itself and the referenced assemblies if second path:
                    if (isSecondPass && !isProcessingCSHTML5Itself)
                    {
                        reflectionOnSeparateAppDomain.LoadAssembly(sourceAssemblyForPass2, loadReferencedAssembliesToo: true, isBridgeBasedVersion: isBridgeBasedVersion, isCoreAssembly: false, nameOfAssembliesThatDoNotContainUserCode: nameOfAssembliesThatDoNotContainUserCode);
                    }

                    bool isSuccess = true;

                    //------- DISPLAY THE PROGRESS -------
                    logger.WriteMessage(operationName + (isSuccess ? " completed in " + executionTimeMeasuring.StopAndGetTimeInSeconds() + " seconds." : " failed.") + "\". IsSecondPass: "******". Source assembly file: \"" + (sourceAssemblyForPass2 ?? "").ToString());

                    return(isSuccess);
                }
            }
            catch (Exception ex)
            {
                if (ReflectionOnSeparateAppDomainHandler.Current != null)
                {
                    ReflectionOnSeparateAppDomainHandler.Current.Dispose();
                }

                logger.WriteError(operationName + " failed: " + ex.ToString());
                return(false);
            }
        }
 /// <summary>
 /// Returns info such as client version, git version of graphene/fc, version of boost, openssl.
 /// </summary>
 /// <returns>Returns compile time info And client And dependencies versions</returns>
 public AboutResponse About()
 {
     try
     {
         var reqname     = CSharpToCpp.GetValue(MethodBase.GetCurrentMethod().Name);
         var result      = SendRequest(reqname);
         var contentdata = JsonConvert.DeserializeObject <AboutResponse>(result);
         return(contentdata);
     }
     catch (Exception ex)
     {
         _logger.WriteError($"Message:{ex.Message} | StackTrace:{ex.StackTrace}");
         throw;
     }
 }
Exemple #29
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var tokenRequestParameters = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                    new KeyValuePair <string, string>("redirect_uri", GenerateRedirectUri()),
                    new KeyValuePair <string, string>("client_secret", Options.ClientSecret),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                };

                var requestContent = new FormUrlEncodedContent(tokenRequestParameters);

                HttpResponseMessage response = await _httpClient.PostAsync(Options.Endpoints.TokenEndpoint, requestContent, Request.CallCancelled);

                response.EnsureSuccessStatusCode();
                string oauthTokenResponse = await response.Content.ReadAsStringAsync();

                JObject oauth2Token = JObject.Parse(oauthTokenResponse);
                string  accessToken = oauth2Token["access_token"].Value <string>();

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                MappedResult <JObject> accountInformation = await _httpClient.DownloadJsonAsync <JObject>(Options.Endpoints.UserInfoEndpoint);

                SurveyMonkeyAuthenticatedContext context = new SurveyMonkeyAuthenticatedContext(Context, _httpClient, Options.AuthenticationType, accountInformation.Result, accessToken);

                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim(ClaimTypes.GivenName, context.FirstName, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim(ClaimTypes.Surname, context.LastName, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:" + Options.AuthenticationType + ":username", context.UserName, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:" + Options.AuthenticationType + ":account_type", context.AccountType, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:" + Options.AuthenticationType + ":language", context.Language, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:" + Options.AuthenticationType + ":date_created", context.DateCreated, Constants.XmlSchemaString, Options.AuthenticationType)
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                //To Do
                if (!string.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, Constants.XmlSchemaString, Options.AuthenticationType));
                }

                await Options.Provider.Authenticated(context);

                context.Properties = properties;

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #30
0
        public async Task ExecuteAsync(ICommandBuildDossier command)
        {
            Dossier           dossier           = new Dossier();
            DossierBuildModel dossierBuildModel = command.ContentType.ContentTypeValue;
            DossierModel      dossierModel      = dossierBuildModel.Dossier;

            IdWorkflowActivity = dossierBuildModel.IdWorkflowActivity;

            try
            {
                if (RetryPolicyEvaluation != null && !string.IsNullOrEmpty(RetryPolicyEvaluation.ReferenceModel))
                {
                    dossierModel = JsonConvert.DeserializeObject <DossierModel>(RetryPolicyEvaluation.ReferenceModel, _serializerSettings);
                }
                else
                {
                    RetryPolicyEvaluation = new EvaluationModel();
                }

                #region [ STEP PREPARE ENTITY ]
                if (!RetryPolicyEvaluation.Steps.Any(d => d.Name == STEP_PREPARE_ENTITY))
                {
                    ProcessPrepareEntityStepEvaluation(dossier, dossierModel);

                    RetryPolicyEvaluation.Steps.Add(new StepModel()
                    {
                        Name           = STEP_PREPARE_ENTITY,
                        LocalReference = JsonConvert.SerializeObject(dossier, _serializerSettings)
                    });
                }
                else
                {
                    StepModel messageStatus = RetryPolicyEvaluation.Steps.First(f => f.Name == STEP_PREPARE_ENTITY);
                    dossier = JsonConvert.DeserializeObject <Dossier>(messageStatus.LocalReference);
                }
                #endregion

                #region [ STEP CREATE ENTITY ]
                if (!RetryPolicyEvaluation.Steps.Any(f => f.Name == STEP_CREATE_ENTITY))
                {
                    dossier.WorkflowName         = dossierBuildModel.WorkflowName;
                    dossier.IdWorkflowActivity   = dossierBuildModel.IdWorkflowActivity;
                    dossier.WorkflowAutoComplete = dossierBuildModel.WorkflowAutoComplete;
                    dossier.WorkflowActions      = dossierBuildModel.WorkflowActions;

                    _logger.WriteDebug(new LogMessage(JsonConvert.SerializeObject(dossier, _serializerSettings)), LogCategories);
                    dossier = await _webApiClient.PostEntityAsync(dossier);

                    _logger.WriteInfo(new LogMessage($"Dossier {dossier.Year}/{dossier.Number:0000000} ({dossier.UniqueId}) has been created"), LogCategories);

                    RetryPolicyEvaluation.Steps.Add(new StepModel()
                    {
                        Name           = STEP_CREATE_ENTITY,
                        LocalReference = JsonConvert.SerializeObject(dossier, _serializerSettings)
                    });
                }
                else
                {
                    StepModel messageStatus = RetryPolicyEvaluation.Steps.First(f => f.Name == STEP_CREATE_ENTITY);
                    dossier = JsonConvert.DeserializeObject <Dossier>(messageStatus.LocalReference);
                }
                #endregion

                #region [ STEP ADD DOSSIER DOCUMENTS ]
                if (!RetryPolicyEvaluation.Steps.Any(f => f.Name == STEP_ADD_DOCUMENTS))
                {
                    if (dossierModel.Documents != null && dossierModel.Documents.Any())
                    {
                        dossier.DossierDocuments = dossierModel.Documents.Select(docModel => new DossierDocument
                        {
                            IdArchiveChain = docModel.IdArchiveChain
                        }).ToList();
                    }
                }
                else
                {
                    StepModel messageStatus = RetryPolicyEvaluation.Steps.First(f => f.Name == STEP_ADD_DOCUMENTS);
                    dossier = JsonConvert.DeserializeObject <Dossier>(messageStatus.LocalReference);
                }
                #endregion

                #region [ STEP UPDATE DOSSIER ]
                if (!RetryPolicyEvaluation.Steps.Any(f => f.Name == STEP_UPDATE_DOSSIER))
                {
                    dossier = await _webApiClient.PutEntityAsync(dossier);

                    RetryPolicyEvaluation.Steps.Add(new StepModel()
                    {
                        Name           = STEP_UPDATE_DOSSIER,
                        LocalReference = JsonConvert.SerializeObject(dossier, _serializerSettings)
                    });
                }
                else
                {
                    StepModel messageStatus = RetryPolicyEvaluation.Steps.First(f => f.Name == STEP_UPDATE_DOSSIER);
                    dossier = JsonConvert.DeserializeObject <Dossier>(messageStatus.LocalReference);
                }
                #endregion

                #region [ STEP COMPLETE DOSSIER BUILD]
                dossierModel.Year             = dossier.Year;
                dossierModel.Number           = dossier.Number;
                dossierModel.Title            = $"Dossier {dossier.Year}/{dossier.Number:0000000}";
                dossierModel.RegistrationDate = dossier.RegistrationDate;
                dossierModel.RegistrationUser = dossier.RegistrationUser;
                dossierModel.LastChangedDate  = dossier.LastChangedDate;
                dossierModel.LastChangedUser  = dossier.LastChangedUser;
                dossierModel.StartDate        = dossier.StartDate;
                dossierModel.Subject          = dossier.Subject;
                dossierModel.DossierType      = (DossierTypeModel)dossier.DossierType;

                dossierBuildModel.Dossier = dossierModel;
                IEventCompleteDossierBuild eventCompleteDossierBuild = new EventCompleteDossierBuild(Guid.NewGuid(), command.CorrelationId ?? dossierBuildModel.UniqueId,
                                                                                                     command.TenantName, command.TenantId, command.TenantAOOId, command.Identity, dossierBuildModel, null);

                if (!await _webApiClient.PushEventAsync(eventCompleteDossierBuild))
                {
                    _logger.WriteError(new LogMessage($"EventCompleteDossierBuild {dossier.GetTitle()} has not been sent"), LogCategories);
                    throw new Exception("IEventCompleteDossierBuild not sent");
                }
                _logger.WriteInfo(new LogMessage($"EventCompleteDossierBuild {eventCompleteDossierBuild.Id} has been sent"), LogCategories);
                #endregion
            }
            catch (Exception ex)
            {
                RetryPolicyEvaluation.ReferenceModel = JsonConvert.SerializeObject(dossierModel, _serializerSettings);

                _logger.WriteError(ex, LogCategories);
                throw new ServiceBusEvaluationException(RetryPolicyEvaluation);
            }
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("client_id", Options.ClientId));
                body.Add(new KeyValuePair <string, string>("client_secret", Options.ClientSecret));

                // Request the token
                var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.Endpoints.TokenEndpoint);
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                requestMessage.Content = new FormUrlEncodedContent(body);
                HttpResponseMessage tokenResponse = await httpClient.SendAsync(requestMessage);

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response    = JsonConvert.DeserializeObject <dynamic>(text);
                string  accessToken = (string)response.access_token;

                // Get the GitHub user
                HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, Options.Endpoints.UserInfoEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken));
                userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage userResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);

                userResponse.EnsureSuccessStatusCode();
                text = await userResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                var context = new GitHubAuthenticatedContext(Context, user, accessToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim("urn:github:name", context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:github:url", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Exemple #32
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string state = null;
                string code  = null;

                IReadableStringCollection query = Request.Query;
                IList <string>            values;

                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }
                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                values = query.GetValues("error");
                if (values != null && values.Count == 1)
                {
                    return(new AuthenticationTicket(null, properties));
                }

                values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                var body = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                    new KeyValuePair <string, string>("client_secret", Options.ClientSecret),
                    new KeyValuePair <string, string>("redirect_uri", redirectUri)
                };

                // Request the token
                var tokenResponse = await _httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));

                tokenResponse.EnsureSuccessStatusCode();
                string content = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                var    response    = JsonConvert.DeserializeObject <JObject>(content);
                string accessToken = response.Value <string>("access_token");

                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var userResponse = await _httpClient.GetAsync(UserInfoEndpoint);

                var userContent = await userResponse.Content.ReadAsStringAsync();

                JObject userJson = null;
                if (userResponse.IsSuccessStatusCode)
                {
                    userJson = JObject.Parse(userContent);
                }

                var context = new IntercomAuthenticatedContext(Context, accessToken, userJson);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!String.IsNullOrEmpty(context.UserId))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #33
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string  code  = null;
                string  state = null;
                JObject id    = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("client_id", Options.ClientId));
                body.Add(new KeyValuePair <string, string>("client_secret", Options.ClientSecret));

                // Request the token
                var httpRequest =
                    new HttpRequestMessage(HttpMethod.Post, String.Format(TokenEndpointFormat, Options.Tenant));
                httpRequest.Content = new FormUrlEncodedContent(body);
                if (Options.RequestLogging)
                {
                    _logger.WriteInformation(httpRequest.ToLogString());
                }
                var httpResponse = await _httpClient.SendAsync(httpRequest);

                httpResponse.EnsureSuccessStatusCode();
                string text = await httpResponse.Content.ReadAsStringAsync();

                if (Options.ResponseLogging)
                {
                    // Note: avoid using one of the Write* methods that takes a format string as input
                    // because the curly brackets from a JSON response will be interpreted as
                    // curly brackets for the format string and function will throw a FormatException
                    _logger.WriteInformation(httpResponse.ToLogString());
                }
                // Deserializes the token response
                JObject response     = JsonConvert.DeserializeObject <JObject>(text);
                string  accessToken  = response.Value <string>("access_token");
                string  scope        = response.Value <string>("scope");
                string  expires      = response.Value <string>("expires_in");
                string  refreshToken = response.Value <string>("refresh_token");
                string  idToken      = response.Value <string>("id_token");

                // id_token should be a Base64 url encoded JSON web token
                string[] segments;
                if (!String.IsNullOrEmpty(idToken) && (segments = idToken.Split('.')).Length == 3)
                {
                    string payload = base64urldecode(segments[1]);
                    if (!String.IsNullOrEmpty(payload))
                    {
                        id = JObject.Parse(payload);
                    }
                }

                var context = new MicrosoftOnlineAuthenticatedContext(Context, id, accessToken, scope, expires, refreshToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrEmpty(context.Subject))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.NameIdentifier, context.Subject, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Upn))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.Upn, context.Upn, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                else
                {
                    // get user email address from UserInfo endpoint
                    string userEmail   = null;
                    var    userRequest = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint);
                    userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    var userResponse = await _httpClient.SendAsync(userRequest);

                    var userContent = await userResponse.Content.ReadAsStringAsync();

                    if (userResponse.IsSuccessStatusCode)
                    {
                        var userJson = JObject.Parse(userContent);
                        userEmail = userJson["EmailAddress"]?.Value <string>();
                    }
                    if (!string.IsNullOrEmpty(userEmail))
                    {
                        context.Email = userEmail;
                        context.Identity.AddClaim(
                            new Claim(ClaimTypes.Email, userEmail, XmlSchemaString, Options.AuthenticationType));
                    }
                }
                if (!string.IsNullOrEmpty(context.GivenName))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.GivenName, context.GivenName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FamilyName))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.Surname, context.FamilyName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
                }

                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }