private static ClaimsIdentity CreateIdentity(int accountId, string userName, ApplicationListItem[] apps)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, accountId.ToString(), ClaimValueTypes.Integer32),
                new Claim(ClaimTypes.Name, userName, ClaimValueTypes.String)
            };

            foreach (var app in apps)
            {
                claims.Add(new Claim(OneTrueClaims.Application, app.Id.ToString(), ClaimValueTypes.Integer32));
                claims.Add(new Claim(OneTrueClaims.ApplicationName, app.Name, ClaimValueTypes.String));
                if (app.IsAdmin)
                {
                    claims.Add(new Claim(OneTrueClaims.ApplicationAdmin, app.Id.ToString(), ClaimValueTypes.Integer32));
                }
            }

            var roles   = accountId == 1 ? new[] { OneTrueClaims.RoleSysAdmin } : new string[0];
            var context = new PrincipalFactoryContext(accountId, userName, roles)
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                Claims             = claims.ToArray()
            };

            return((ClaimsIdentity)PrincipalFactory.CreateAsync(context).Result.Identity);
        }
Ejemplo n.º 2
0
        private void ConfigureAuth(IAppBuilder app)
        {
            var type = ConfigurationManager.AppSettings["PrincipalFactoryType"];

            if (type != null)
            {
                PrincipalFactory.Configure(type);
            }

            var provider = new CookieAuthenticationProvider
            {
                OnApplyRedirect = ctx =>
                {
                    if (!IsApiRequest(ctx.Request) && !ctx.Request.Headers.ContainsKey("X-Requested-With"))
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                }
            };

            var loginUrl = "/Account/Login"; //VirtualPathUtility.ToAbsolute("~/Account/Login");

            BaseViewPage.LoginUrl = loginUrl;
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                ExpireTimeSpan     = TimeSpan.FromDays(14),
                LoginPath          = new PathString(loginUrl),
                Provider           = provider,
                SessionStore       = new SessionStoreMediator()
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
 public AttachCustomPrincipal(GetTheCurrentTicket ticket_factory, PrincipalFactory principal_factory,
                              GetTheCurrentUserIDFromTicket id_mapper, PrincipalSwitch principal_switch)
 {
   this.ticket_factory = ticket_factory;
   this.principal_factory = principal_factory;
   this.id_mapper = id_mapper;
   this.principal_switch = principal_switch;
 }
Ejemplo n.º 4
0
#pragma warning disable 1998
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
#pragma warning restore 1998
        {
            var p = context.Principal as ClaimsPrincipal;

            if (p != null && p.Identity.IsAuthenticated)
            {
                return;
            }

            IEnumerable <string> apiKeys;
            IEnumerable <string> tokens;

            if (!context.Request.Headers.TryGetValues("X-Api-Key", out apiKeys) ||
                !context.Request.Headers.TryGetValues("X-Api-Signature", out tokens))
            {
                return;
            }

            using (var scope = GlobalConfiguration.Configuration.DependencyResolver.BeginScope())
            {
                var    repos = (IApiKeyRepository)scope.GetService(typeof(IApiKeyRepository));
                ApiKey key;
                try
                {
                    key = await repos.GetByKeyAsync(apiKeys.First());
                }
                catch (EntityNotFoundException)
                {
                    context.ErrorResult = new AuthenticationFailureResult("Invalid/unknown API key", context.Request);
                    return;
                }

                var content = await context.Request.Content.ReadAsByteArrayAsync();

                if (!key.ValidateSignature(tokens.First(), content))
                {
                    context.ErrorResult =
                        new AuthenticationFailureResult(
                            "Body could not be signed by the shared secret. Verify your client configuration.",
                            context.Request);
                    return;
                }

                var claims         = key.Claims;
                var factoryContext = new PrincipalFactoryContext(0, key.GeneratedKey, new[] { CoderrClaims.RoleSystem })
                {
                    AuthenticationType = "ApiKey",
                    Claims             = claims
                };
                var principal = await PrincipalFactory.CreateAsync(factoryContext);

                context.Principal       = principal;
                Thread.CurrentPrincipal = principal;
            }
        }
Ejemplo n.º 5
0
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var user = await UserService.GetUserAsync(context.Subject);

            var principal = await PrincipalFactory.CreateAsync(user);

            foreach (var claim in principal.Claims)
            {
                context.IssuedClaims.Add(claim);
            }
        }
Ejemplo n.º 6
0
        private bool AuthenticateUser(ITcpChannel channel, HttpRequest request)
        {
            if (channel.Data["Principal"] != null)
            {
                Thread.CurrentPrincipal = (IPrincipal)channel.Data["Principal"];
                return(true);
            }

            try
            {
                var user = Authenticator.Authenticate(request);
                if (user == null)
                {
                    return(true);
                }

                if (PrincipalFactory != null)
                {
                    var ctx = new PrincipalFactoryContext(request, user);
                    Thread.CurrentPrincipal   = PrincipalFactory.Create(ctx);
                    channel.Data["Principal"] = Thread.CurrentPrincipal;
                    return(true);
                }

                var roles = user as IUserWithRoles;
                if (roles == null)
                {
                    throw new InvalidOperationException(
                              "You must specify a PrincipalFactory if you do not return a IUserWithRoles from your IAccountService.");
                }

                Thread.CurrentPrincipal   = new GenericPrincipal(new GenericIdentity(user.Username), roles.RoleNames);
                channel.Data["Principal"] = Thread.CurrentPrincipal;
            }
            catch (HttpException ex)
            {
                if (Logger != null)
                {
                    Logger("Authentication failed.\r\nException:\r\n" + ex.ToString());
                }
                var response = request.CreateResponse();
                response.StatusCode   = ex.HttpCode;
                response.ReasonPhrase = FirstLine(ex.Message);
                channel.Send(response);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 7
0
        public void Constructs_principal_with_roles()
        {
            MockRepository mocks    = new MockRepository();
            IIdentity      identity = mocks.CreateMock <IIdentity>();

            mocks.ReplayAll();

            using (mocks.Playback())
            {
                IPrincipalFactory factory   = new PrincipalFactory();
                IPrincipal        principal = factory.CreatePrincipal(identity, "Administrator", "Other Role");

                Assert.That(principal.IsInRole("Administrator"));
                Assert.That(principal.IsInRole("Other Role"));
                Assert.That(!principal.IsInRole("MyRole"));
            }

            mocks.VerifyAll();
        }
Ejemplo n.º 8
0
        protected override async Task <AuthenticationTicket> HandleAuthenticateAsync()
        {
            var header = Request.Headers["Authorization"];

            if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer "))
            {
                return(null);
            }

            var user      = header.Substring(7);
            var principal = PrincipalFactory.Get(user);

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

            return(new AuthenticationTicket(new ClaimsPrincipal(principal), new AuthenticationProperties(), "Bearer"));
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     Execute the request and generate a reply.
        /// </summary>
        /// <param name="request">Request to execute</param>
        /// <returns>
        ///     Task which will contain the reply once completed.
        /// </returns>
        public async Task <ActivateAccountReply> ExecuteAsync(ActivateAccount request)
        {
            var account = await _repository.FindByActivationKeyAsync(request.ActivationKey);

            if (account == null)
            {
                throw new ArgumentOutOfRangeException("ActivationKey", request.ActivationKey,
                                                      "Key was not found.");
            }

            account.Activate();
            await _repository.UpdateAsync(account);

            var query = new GetApplicationList {
                AccountId = account.Id
            };
            var apps = await _queryBus.QueryAsync(query);

            var claims =
                apps.Select(x => new Claim(OneTrueClaims.Application, x.Id.ToString(), ClaimValueTypes.Integer32))
                .ToArray();

            if (ClaimsPrincipal.Current.IsAccount(account.Id))
            {
                var context = new PrincipalFactoryContext(account.Id, account.UserName, new string[0])
                {
                    Claims = claims
                };
                var identity = await PrincipalFactory.CreateAsync(context);

                identity.AddUpdateCredentialClaim();
                Thread.CurrentPrincipal = identity;
            }

            var evt = new AccountActivated(account.Id, account.UserName)
            {
                EmailAddress = account.Email
            };
            await _eventBus.PublishAsync(evt);

            return(new ActivateAccountReply(account.Id, account.UserName));
        }
        // Based on https://stackoverflow.com/a/44322425/1249506
        public async Task <IdentityServerToken> GetIdentityServerTokenForUserAsync(User user)
        {
            var request          = new TokenCreationRequest();
            var identityPricipal = await PrincipalFactory.CreateAsync(user);

            var identityUser =
                new IdentityServerUser(user.Id.ToString())
            {
                AdditionalClaims   = identityPricipal.Claims.ToArray(),
                DisplayName        = user.UserName,
                AuthenticationTime = DateTime.UtcNow,
                IdentityProvider   = IdentityServerConstants.LocalIdentityProvider
            };

            request.Subject = identityUser.CreatePrincipal();
            request.IncludeAllIdentityClaims = true;
            request.ValidatedRequest         = new ValidatedRequest
            {
                Subject = request.Subject,
            };

            var client = await ClientStore.FindClientByIdAsync(ClientId);

            request.ValidatedRequest.SetClient(client);
            request.Resources =
                new Resources(await ResourceStore.FindEnabledIdentityResourcesByScopeAsync(client.AllowedScopes),
                              await ResourceStore.FindApiResourcesByScopeAsync(client.AllowedScopes))
            {
                OfflineAccess = client.AllowOfflineAccess
            };

            request.ValidatedRequest.Options      = Options;
            request.ValidatedRequest.ClientClaims = identityUser.AdditionalClaims;

            var token = await TokenService.CreateAccessTokenAsync(request);

            var accessToken = await TokenService.CreateSecurityTokenAsync(token);

            var refreshToken = await RefreshTokenService.CreateRefreshTokenAsync(request.Subject, token, client);

            return(new IdentityServerToken(token, accessToken, refreshToken));
        }
Ejemplo n.º 11
0
        protected override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            var header = Request.Headers["Authorization"].ToString();

            if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer "))
            {
                return(Task.FromResult(AuthenticateResult.Skip()));
            }

            var user      = header.Substring(7);
            var principal = PrincipalFactory.Get(user);

            if (principal == null)
            {
                return(Task.FromResult(AuthenticateResult.Fail("No such user")));
            }

            var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme);

            return(Task.FromResult(AuthenticateResult.Success(ticket)));
        }
Ejemplo n.º 12
0
        public async Task <AcceptInvitationReply> ExecuteAsync(AcceptInvitation request)
        {
            var invitation = await _repository.GetByInvitationKeyAsync(request.InvitationKey);

            if (invitation == null)
            {
                _logger.Error("Failed to find invitation key" + request.InvitationKey);
                return(null);
            }
            await _repository.DeleteAsync(request.InvitationKey);

            Account account;

            if (request.AccountId == 0)
            {
                account = new Account(request.UserName, request.Password);
                account.SetVerifiedEmail(request.AcceptedEmail);
                account.Activate();
                account.Login(request.Password);
                await _accountRepository.CreateAsync(account);
            }
            else
            {
                account = await _accountRepository.GetByIdAsync(request.AccountId);

                account.SetVerifiedEmail(request.AcceptedEmail);
            }

            var inviter = await _accountRepository.FindByUserNameAsync(invitation.InvitedBy);

            if (ClaimsPrincipal.Current.IsAccount(account.Id))
            {
                var claims = invitation.Invitations
                             .Select(
                    x => new Claim(OneTrueClaims.Application, x.ApplicationId.ToString(), ClaimValueTypes.Integer32))
                             .ToList();

                var context = new PrincipalFactoryContext(account.Id, account.UserName, new string[0])
                {
                    Claims             = claims.ToArray(),
                    AuthenticationType = "Invite"
                };
                var principal = await PrincipalFactory.CreateAsync(context);

                principal.AddUpdateCredentialClaim();
                Thread.CurrentPrincipal = principal;
            }

            // Account have not been created before the invitation was accepted.
            if (request.AccountId == 0)
            {
                await _eventBus.PublishAsync(new AccountRegistered(account.Id, account.UserName));

                await _eventBus.PublishAsync(new AccountActivated(account.Id, account.UserName)
                {
                    EmailAddress = account.Email
                });
            }

            var e = new InvitationAccepted(account.Id, invitation.InvitedBy, account.UserName)
            {
                InvitedEmailAddress  = invitation.EmailToInvitedUser,
                AcceptedEmailAddress = request.AcceptedEmail,
                ApplicationIds       = invitation.Invitations.Select(x => x.ApplicationId).ToArray()
            };
            await _eventBus.PublishAsync(e);

            return(new AcceptInvitationReply(account.Id, account.UserName));
        }
Ejemplo n.º 13
0
 public IEnumerable <ClaimsIdentity> Get(string name)
 {
     return(PrincipalFactory.Get(name).Identities);
 }
Ejemplo n.º 14
0
        public override async void Create()
        {
            this.mainWindow.RemoveAll();
            this.mainWindow.Title = Strings.WindowTitle;
            var result = await this.messageBoxService.Show(@$ "No encrypted profile found! Do you want to create a new XDS ID?

We were searching in:
{this.cancellation.DataDirRoot}
",
                                                           Strings.WindowTitle, RequestButton.YesNo, RequestImage.None);

            if (result == RequestResult.No)
            {
                Application.Top.Running = false;
                return;
            }

            this.stopwatch.Reset();

            // Demo #1 - Use System.Timer (and threading)
            var idGenerationControl = new IdGenerationControl("Generate XDS ID")
            {
                Width = Dim.Percent(100),
            };

            idGenerationControl.OnCaptureEntropyButtonClick = async() =>
            {
                if (!this.stopwatch.IsRunning)
                {
                    RandomCapture.Reset();
                    this.stopwatch.Restart();
                    idGenerationControl.ActivityProgressBar.Fraction = 0f;
                    idGenerationControl.LabelProgress.Text           = "0 %";
                }



                for (var i = 0; i < 50; i++)
                {
                    if (RandomCapture.BytesGenerated == RandomCapture.BytesNeeded)
                    {
                        break;
                    }

                    var data = RandomCapture.CaputureFromPointer(Math.Abs(DateTime.Now.Ticks.GetHashCode() + Guid.NewGuid().GetHashCode()), this.stopwatch.ElapsedMilliseconds);
                    idGenerationControl.ActivityProgressBar.Fraction = (float)data.Percent / 100f;
                    idGenerationControl.LabelProgress.Text           = data.Progress;
                }

                if (RandomCapture.BytesGenerated == RandomCapture.BytesNeeded)
                {
                    idGenerationControl.LabelDone.Text = "Complete. Creating your XDS ID...";

                    var entropy96 = this.xdsSecService.CombinePseudoRandomWithRandom(RandomCapture.GeneratedBytes, 3 * 32).Result;

                    var principalFactory = new PrincipalFactory(this.xdsSecService);
                    principalFactory.CreateMnemonics(entropy96);

                    var principal = principalFactory.GetXDSPrincipal();

                    this.onboardingViewModel.OnboardingGenerateIdentity(principal, principalFactory.MasterSentence);

                    await Task.Delay(600);

                    idGenerationControl.LabelDone.Text                = "Complete. Creating your XDS ID...done.";
                    idGenerationControl.TextFieldYourId.Text          = $"{this.onboardingViewModel.ChatId}";
                    idGenerationControl.TextFieldYourId.Width         = Dim.Fill(); // has zero width, make it visible now
                    idGenerationControl.TextFieldYourAddress.Text     = $"{this.onboardingViewModel.DefaultAddress}";
                    idGenerationControl.TextFieldYourAddress.Width    = Dim.Fill();
                    idGenerationControl.TextFieldYourId.ReadOnly      = true;
                    idGenerationControl.TextFieldYourAddress.ReadOnly = true;

                    idGenerationControl.LabelRecovery.Text = "Recovery Sentence:";

                    var textFieldRecoveryCode = new TextField
                    {
                        X      = idGenerationControl.LabelRecovery.X,
                        Y      = idGenerationControl.LabelRecovery.Y + 1,
                        Width  = Dim.Fill(),
                        Height = 5,
                    };

                    textFieldRecoveryCode.ReadOnly    = true;
                    textFieldRecoveryCode.LayoutStyle = LayoutStyle.Computed;
                    textFieldRecoveryCode.Text        = principalFactory.MasterSentence;
                    idGenerationControl.Add(textFieldRecoveryCode);

                    textFieldRecoveryCode.KeyPress += args =>
                    {
                        if (!textFieldRecoveryCode.HasFocus)
                        {
                            return;
                        }

                        if (args.KeyEvent.Key == Key.ControlA)
                        {
                            textFieldRecoveryCode.SelectedStart  = 0;
                            textFieldRecoveryCode.SelectedLength = textFieldRecoveryCode.Text.Length;
                            textFieldRecoveryCode.SelectedText   = principalFactory.MasterSentence;
                            textFieldRecoveryCode.SetNeedsDisplay(textFieldRecoveryCode.Bounds);
                            args.Handled = true;
                        }
                    };


                    var labelYourName =
                        new Label("Your Name (not visible to others):")
                    {
                        X = textFieldRecoveryCode.X,
                        Y = textFieldRecoveryCode.Y + 2,
                    };
                    idGenerationControl.Add(labelYourName);

                    var textFieldName = new TextField("Anonymous")
                    {
                        X     = labelYourName.X,
                        Y     = labelYourName.Y + 1,
                        Width = Dim.Fill()
                    };
                    idGenerationControl.Add(textFieldName);

                    var buttonContinue = new Button("Continue")
                    {
                        X       = textFieldName.X,
                        Y       = textFieldName.Y + 3,
                        Clicked = () =>
                        {
                            this.onboardingViewModel.Name = string.IsNullOrWhiteSpace(textFieldName.Text.ToString())
                                ? "Anonymous"
                                : textFieldName.Text.ToString();
                            this.onboardingViewModel.PictureBytes =
                                Guid.NewGuid().ToByteArray(); // pass the checks for null and all-bytes-zero
                            NavigationService.ShowSetPassphraseView();
                        }
                    };
                    idGenerationControl.Add(buttonContinue);
                    buttonContinue.SetFocus();

                    var buttonBackup = new Button("Backup")
                    {
                        X       = Pos.Right(buttonContinue) + Style.SpaceBetweenButtons,
                        Y       = textFieldName.Y + 3,
                        Clicked = () =>
                        {
                            var exportFilePath = Path.Combine(this.cancellation.GetTempDir(true), this.onboardingViewModel.ChatId + ".txt");

                            var choice = MessageBox.ErrorQuery("Cleartext Export",
                                                               $"Export your XDS ID, XDS Address and Recovery Sentence? Path: {exportFilePath}", "YES", "NO");
                            if (choice == 0)
                            {
                                var sb = new StringBuilder();
                                sb.AppendLine("WARNING - THIS FILE CONTAINS SENSITIVE PRIVATE INFORMATION DESCRIBING YOUR XDS ID AND WALLET PRIVATE KEYS.");
                                sb.AppendLine("Using this information, an attacker can decrypt your messages, impersonate and steal your identity and access the XDS coins in your wallet.");
                                sb.AppendLine("It's strongly recommended you create your XDS identity on an air-gapped system and keep this information always offline in a safe place. When you do not need your XDS identity any more, you should destroy this information, so that nobody else can pretend to be you.");
                                sb.AppendLine("====================================");
                                sb.AppendLine($"XDS ID={this.onboardingViewModel.ChatId}");
                                sb.AppendLine($"XDS Address={this.onboardingViewModel.DefaultAddress}");
                                sb.AppendLine($"Recovery Sentence={this.onboardingViewModel.MasterSentence}");
                                File.WriteAllText(exportFilePath, sb.ToString());
                            }

                            if (choice == 0)
                            {
                                MessageBox.ErrorQuery("Success",
                                                      $"Recovery sentence saved to: {exportFilePath}\nPlease move this file to a safe place (e.g. USB stick).\nWE WILL DELETE THE TEMP DIRECTORY WHEN YOU QUIT THE APP!", "OK");
                            }
                        }
                    };
                    idGenerationControl.Add(buttonBackup);
                }
            };


            this.mainWindow.Add(idGenerationControl);



            idGenerationControl.EntropyButton.SetFocus();
        }
Ejemplo n.º 15
0
 public SessionController(IServiceBus bus, PrincipalFactory principalFactory)
 {
     this.bus = bus;
     this.principalFactory = principalFactory;
 }