Ejemplo n.º 1
0
        public void PopulateSession(SignInContext sign_in, bool is_refresh = false)
        {
            IdToken            = sign_in.IdToken;
            AccessToken        = sign_in.AccessToken;
            TokenIssuedServer  = sign_in.TokenIssued;
            TokenExpiresServer = sign_in.Expires;

            if (!is_refresh)
            {
                UserName     = sign_in.UserName;
                UserPassword = sign_in.UserPassword;
                RefreshToken = sign_in.RefreshToken;

                MyApp.AppP.UserName     = UserName;
                MyApp.AppP.UserID       = GrabUserID(IdToken);
                MyApp.AppP.Password     = Encryption.Encrypt(UserPassword);
                MyApp.AppP.RefreshToken = Encryption.Encrypt(RefreshToken);
            }


            MyApp.AppP.IdToken      = Encryption.Encrypt(IdToken);
            MyApp.AppP.AccessToken  = Encryption.Encrypt(AccessToken);
            MyApp.AppP.TokenIssued  = TokenIssuedServer;
            MyApp.AppP.TokenExpires = TokenExpiresServer;

            Debug.WriteLine($"From:{this.GetType().Name} PopulateSession, Ir refresh:{is_refresh}, \nUserName = {UserName}\n" +
                            $"UserPassword = {UserPassword}\n" +
                            $"IdToken = {sign_in.IdToken}\n" +
                            $"RefreshToken = {RefreshToken}\n" +
                            $"AccessToken = {sign_in.AccessToken}\n" +
                            $"TokenIssuedServer = {sign_in.TokenIssued}\n" +
                            $"TokenExpiresServer = {sign_in.Expires}\n");
            //data to store in app
        }
Ejemplo n.º 2
0
        public override async Task SignInAsync(string authenticationScheme, ClaimsPrincipal principal, AuthenticationProperties properties)
        {
            if (string.IsNullOrEmpty(authenticationScheme))
            {
                throw new ArgumentException(nameof(authenticationScheme));
            }

            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            var handler = HttpAuthenticationFeature.Handler;

            var signInContext = new SignInContext(authenticationScheme, principal, properties?.Items);

            if (handler != null)
            {
                await handler.SignInAsync(signInContext);
            }

            if (!signInContext.Accepted)
            {
                throw new InvalidOperationException($"No authentication handler is configured to handle the scheme: {authenticationScheme}");
            }
        }
        public void CreateSessionId(SignInContext context)
        {
            var sid = CryptoRandom.CreateUniqueId();

            context.Properties[OidcConstants.EndSessionRequest.Sid] = sid;
            IssueSessionIdCookie(sid);
        }
        private void signInControl_AfterSignIn(SignInContext context)
        {
			if (context.ResultType == SignInResultType.Success)
			{
				if (PassportSignInSettings.GetConfig().UseSimulateTime)
				{
					context.SignInInfo.Properties["SimulateTime"] = this.simulateDate.Value;

					IPersistTimePoint persister = TimePointSimulationSettings.GetConfig().Persister;

					if (persister != null)
					{
						OguObjectCollection<IUser> users = OguMechanismFactory.GetMechanism().GetObjects<IUser>(SearchOUIDType.LogOnName, context.SignInInfo.UserID);

						if (users.Count > 0)
						{
							persister.SaveTimePoint(users[0].ID, this.simulateDate.Value);

							TimePointContext tpc = new TimePointContext();

							tpc.UseCurrentTime = this.simulateDate.Value == DateTime.MinValue;
							tpc.SimulatedTime = this.simulateDate.Value;

							tpc.SaveToCookie();
						}
					}
				}
			}
        }
Ejemplo n.º 5
0
        public override async Task SignInAsync(string authenticationScheme, ClaimsPrincipal principal, AuthenticationProperties properties)
        {
            if (authenticationScheme == null)
            {
                throw new ArgumentNullException(nameof(authenticationScheme));
            }

            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            var handler = HttpAuthenticationFeature.Handler;

            var signInContext = new SignInContext(authenticationScheme, principal, properties?.Items);

            if (handler != null)
            {
                await handler.SignInAsync(signInContext);
            }

            if (!signInContext.Accepted)
            {
                throw new InvalidOperationException($"The following authentication scheme was not accepted: {authenticationScheme}");
            }
        }
Ejemplo n.º 6
0
        private void signInControl_AfterSignIn(SignInContext context)
        {
            if (context.ResultType == SignInResultType.Success)
            {
                if (PassportSignInSettings.GetConfig().UseSimulateTime)
                {
                    context.SignInInfo.Properties["SimulateTime"] = this.simulateDate.Value;

                    IPersistTimePoint persister = TimePointSimulationSettings.GetConfig().Persister;

                    if (persister != null)
                    {
                        OguObjectCollection <IUser> users = OguMechanismFactory.GetMechanism().GetObjects <IUser>(SearchOUIDType.LogOnName, context.SignInInfo.UserID);

                        if (users.Count > 0)
                        {
                            persister.SaveTimePoint(users[0].ID, this.simulateDate.Value);

                            TimePointContext tpc = new TimePointContext();

                            tpc.UseCurrentTime = this.simulateDate.Value == DateTime.MinValue;
                            tpc.SimulatedTime  = this.simulateDate.Value;

                            tpc.SaveToCookie();
                        }
                    }
                }
            }
        }
        protected override async Task HandleSignInAsync(SignInContext context)
        {
            //no real need to call base as it doesn't do anything
            await base.HandleSignInAsync(context);

            SignInAccepted = true;
        }
Ejemplo n.º 8
0
        private async Task <string> StartInitializeUserAsync(SignInContext signInContext, IAsyncCollector <EventGridEvent> collector, ILogger log)
        {
            string id                           = Guid.NewGuid().ToString();
            string location                     = $"{serviceBaseAddress}/UserInit/{id}";
            UserInitializeStatus status         = new UserInitializeStatus(id, false);
            DataAccessResult     entryAddResult = await dataService.SetUserInitializeStatusAsync(status);

            if (!entryAddResult.Success)
            {
                log.LogWarning("Cannot add user initialize status to database. Status {statusCode}", entryAddResult.StatusCode);
            }
            try
            {
                var eventGridEvent = new EventGridEvent(
                    id: $"UserInit-{Guid.NewGuid()}",
                    subject: signInContext.SignedInUser,
                    data: new Models.UserInitializeCommand(signInContext, id),
                    eventType: "DL444.Ucqu.UserInit",
                    eventTime: DateTime.UtcNow,
                    dataVersion: "1.0"
                    );
                await collector.AddAsync(eventGridEvent);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Cannot trigger user initialization.");
            }
            return(location);
        }
Ejemplo n.º 9
0
        public void CreateSessionId_when_user_is_anonymous_should_generate_new_sid()
        {
            var ctx = new SignInContext(_scheme, IdentityServerPrincipal.Create("123", "bob"), null);

            _subject.CreateSessionId(ctx);
            ctx.Properties["sid"].Should().NotBeNull();
        }
Ejemplo n.º 10
0
 public async Task SignInAsync(SignInContext context)
 {
     if (context.AuthenticationScheme == _options.AuthenticationOptions.EffectiveAuthenticationScheme)
     {
         AugmentContext(context);
     }
     await _handler.SignInAsync(context);
 }
Ejemplo n.º 11
0
 public Task SignInAsync(SignInContext context)
 {
     if (PriorHandler != null)
     {
         return(PriorHandler.SignInAsync(context));
     }
     return(Task.FromResult(0));
 }
        protected override Task HandleSignInAsync(SignInContext context)
        {
            var ticket = new AuthenticationTicket(context.Principal,
                                                  new AuthenticationProperties(context.Properties),
                                                  context.AuthenticationScheme);

            return(HandleSignInAsync(ticket));
        }
Ejemplo n.º 13
0
 public Task SignInAsync(SignInContext context)
 {
     // Not supported, fall through
     if (PriorHandler != null)
     {
         return(PriorHandler.SignInAsync(context));
     }
     return(Task.FromResult(0));
 }
Ejemplo n.º 14
0
        public void CreateSessionId(SignInContext context)
        {
            if (!context.Properties.ContainsKey(SessionIdKey))
            {
                context.Properties[SessionIdKey] = CryptoRandom.CreateUniqueId(16);
            }

            IssueSessionIdCookie(context.Properties[SessionIdKey]);
        }
        public Task SignInAsync(SignInContext context)
        {
            if (Scheme == null || context.AuthenticationScheme == Scheme)
            {
                context.Accept();
            }

            return(Task.FromResult(0));
        }
Ejemplo n.º 16
0
        public void CreateSessionId(SignInContext context)
        {
            if (!context.Properties.ContainsKey(OidcConstants.EndSessionRequest.Sid))
            {
                context.Properties[OidcConstants.EndSessionRequest.Sid] = CryptoRandom.CreateUniqueId();
            }

            IssueSessionIdCookie(context.Properties[OidcConstants.EndSessionRequest.Sid]);
        }
Ejemplo n.º 17
0
 public Task SignInAsync(SignInContext context)
 {
     if (context.Principal.Identity == null)
     {
         throw new InvalidOperationException("Principal has no identity");
     }
     context.Accept();
     return(Task.FromResult(0));
 }
 public async Task SignInAsync(SignInContext context)
 {
     if (context.AuthenticationScheme == _options.Authentication.EffectiveAuthenticationScheme)
     {
         AugmentContext(context);
         await RaiseSignInEventAsync(context.Principal);
     }
     await _handler.SignInAsync(context);
 }
        private void AugmentContext(SignInContext context)
        {
            _logger.LogDebug("Augmenting SignInContext");

            context.Principal.AssertRequiredClaims();
            context.Principal.AugmentMissingClaims();

            _sessionId.CreateSessionId(context);
        }
        public Task SignInAsync(SignInContext context)
        {
            // Not supported, fall through
            if (PriorHandler != null)
            {
                return(PriorHandler.SignInAsync(context));
            }

            return(TaskCache.CompletedTask);
        }
Ejemplo n.º 21
0
        public void CreateSessionId_when_user_is_authenticated_but_different_sub_should_create_new_sid()
        {
            _stubAuthHandler.User = _user;
            _stubAuthHandler.Properties.Add("sid", "999");

            var ctx = new SignInContext(_scheme, IdentityServerPrincipal.Create("456", "alice"), null);

            _subject.CreateSessionId(ctx);
            ctx.Properties["sid"].Should().NotBeNull();
            ctx.Properties["sid"].Should().NotBe("999");
        }
        public void CreateSessionId_when_user_is_authenticated_should_generate_new_sid()
        {
            _stubAuthHandler.User = _user;
            _stubAuthHandler.Properties.Add("sid", "999");

            var ctx = new SignInContext(_scheme, IdentityServerPrincipal.Create("123", "bob"), null);

            _subject.CreateSessionId(ctx);
            ctx.Properties[DefaultUserSession.SessionIdKey].Should().NotBeNull();
            ctx.Properties[DefaultUserSession.SessionIdKey].Should().NotBe("999");
        }
Ejemplo n.º 23
0
        private static void SetCultureInfo(SignInContext context, string language)
        {
            context.SignInInfo.Properties["Culture"] = language;

            IUserCultureInfoAccessor accessor = UserCultureInfoSettings.GetConfig().UserCultureInfoAccessor;

            if (accessor != null)
            {
                accessor.SaveUserLanguageID(HttpContext.Current.User.Identity.Name, language);
            }
        }
        protected override Task HandleSignInAsync(SignInContext context)
        {
            var ticket      = new AuthenticationTicket(context.Principal, null, Options.AuthenticationScheme);
            var ticketValue = Options.TicketDataFormat.Protect(ticket, GetTlsTokenBinding());

            Context.Session.SetString(Options.CookieName(Context), ticketValue);
#if NET451
            return(Task.FromResult(0));
#else
            return(Task.CompletedTask);
#endif
        }
        protected override async Task HandleSignInAsync(SignInContext signIn)
        {
            var signingInContext = new BearerSigningInContext(Context, Options, signIn.Principal, new AuthenticationProperties(signIn.Properties));
            await Options.Events.SigningIn(signingInContext);

            var ticket = new AuthenticationTicket(signingInContext.Principal, signingInContext.Properties, Options.AuthenticationScheme);

            ApplyBearer(ticket);

            var signedInContext = new BearerSignedInContext(Context, Options, signingInContext.Principal, signingInContext.Properties);
            await Options.Events.SignedIn(signedInContext);
        }
        protected override Task HandleSignInAsync(SignInContext context)
        {
            var ticket      = new AuthenticationTicket(context.Principal, null, Options.AuthenticationScheme);
            var cookieValue = Options.TicketDataFormat.Protect(ticket, GetTlsTokenBinding());

            Response.Cookies.Append(Options.CookieName(Context), cookieValue, new CookieOptions
            {
                Domain  = Options.CookieDomain(Context),
                Expires = new DateTimeOffset(DateTime.Now.Add(Options.ExpireTime(Context))),
                Path    = Options.CookiePath(Context)
            });
            return(Task.FromResult(0));
        }
Ejemplo n.º 27
0
		protected void signInControl_AfterSignIn(SignInContext context)
		{
			if (context.ResultType == SignInResultType.Success)
			{
				string consistentID = PassportSignInSettings.GetConfig().UserIDConverter.GetUserConsistentID(context.UserID);

				OpenIDBinding binding = new OpenIDBinding();

				binding.UserID = consistentID;
				binding.OpenID = Request.QueryString.GetValue("openID", string.Empty);
				binding.OpenIDType = Request.QueryString.GetValue("openIDType", string.Empty);

				PassportSignInSettings.GetConfig().PersistOpenIDBinding.SaveOpenIDBinding(binding);
			}
		}
Ejemplo n.º 28
0
        protected void signInControl_AfterSignIn(SignInContext context)
        {
            if (context.ResultType == SignInResultType.Success)
            {
                string consistentID = PassportSignInSettings.GetConfig().UserIDConverter.GetUserConsistentID(context.UserID);

                OpenIDBinding binding = new OpenIDBinding();

                binding.UserID     = consistentID;
                binding.OpenID     = Request.QueryString.GetValue("openID", string.Empty);
                binding.OpenIDType = Request.QueryString.GetValue("openIDType", string.Empty);

                PassportSignInSettings.GetConfig().PersistOpenIDBinding.SaveOpenIDBinding(binding);
            }
        }
Ejemplo n.º 29
0
        public async Task SignInAsync(SignInContext context)
        {
            if (ShouldHandleScheme(context.AuthenticationScheme, handleAutomatic: false))
            {
                SignInAccepted = true;
                await HandleSignInAsync(context);

                Logger.AuthenticationSchemeSignedIn(Options.AuthenticationScheme);
                context.Accept();
            }
            else if (PriorHandler != null)
            {
                await PriorHandler.SignInAsync(context);
            }
        }
Ejemplo n.º 30
0
        public void CreateSessionId_should_issue_session_id_cookie()
        {
            var ctx = new SignInContext(_scheme, IdentityServerPrincipal.Create("456", "alice"), null);

            _subject.CreateSessionId(ctx);

            var cookieContainer = new CookieContainer();
            var cookies         = _mockHttpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value);

            cookieContainer.SetCookies(new Uri("http://server"), string.Join(",", cookies));
            _mockHttpContext.HttpContext.Response.Headers.Clear();

            var cookie = cookieContainer.GetCookies(new Uri("http://server")).Cast <Cookie>().Where(x => x.Name == _subject.GetCookieName()).FirstOrDefault();

            cookie.Value.Should().Be(ctx.Properties["sid"]);
        }
        protected override async Task HandleSignInAsync(SignInContext context)
        {
            WsFedSignInContext signInContext = context as WsFedSignInContext;
            ClaimsPrincipal    principal     = GetClaimsPrincipal(signInContext.SignInMessage);

            if (principal != null)
            {
                WsFedSignInContext newContext = new WsFedSignInContext(context.AuthenticationScheme, principal, context.Properties, null, signInContext.ReturnUrl);
                await base.HandleSignInAsync(newContext);

                return;
            }

            //Couldn't get a principal even though we've said sign in, so send to forbidden - could be the wrong STS environment, or incorrect certificate config, or some other accidental or nefarious reason for this.
            ChallengeContext cc = new ChallengeContext(Options.AuthenticationScheme);
            await base.HandleForbiddenAsync(cc);
        }
Ejemplo n.º 32
0
        public async Task NewProvider_InsertsProviderRecord()
        {
            // Arrange
            var providerId = await TestData.CreateProvider();

            var provider = await CosmosDbQueryDispatcher.Object.ExecuteQuery(new GetProviderById()
            {
                ProviderId = providerId
            });

            var signInContext = new SignInContext(new System.Security.Claims.ClaimsPrincipal())
            {
                Provider      = provider,
                ProviderUkprn = provider.Ukprn,
                UserInfo      = new AuthenticatedUserInfo()
                {
                    CurrentProviderId = providerId,
                    Email             = "*****@*****.**",
                    FirstName         = "Test",
                    LastName          = "Guy",
                    Role   = RoleNames.ProviderSuperUser,
                    UserId = Guid.NewGuid().ToString()
                }
            };

            // Act
            await WithSqlQueryDispatcher(async dispatcher =>
            {
                var action = new EnsureProviderExistsSignInAction(dispatcher);

                await action.OnUserSignedIn(signInContext);
            });

            // Assert
            var rows = await WithSqlQueryDispatcher(dispatcher =>
            {
                var connection = dispatcher.Transaction.Connection;
                return(connection.QuerySingleAsync <int>(
                           "select count(*) from Pttcd.Providers where ProviderId = @ProviderId",
                           new { ProviderId = providerId },
                           dispatcher.Transaction));
            });

            Assert.Equal(1, rows);
        }
 internal void FireAfterSignIn(SignInContext context)
 {
     if (AfterSignIn != null)
         AfterSignIn(context);
 }
        public virtual void SignIn(ISignInContext context)
        {
            if (ShouldHandleScheme(context.AuthenticationScheme))
            {
                SignInContext = new SignInContext(context.Principal, new AuthenticationProperties(context.Properties));
                SignOutContext = null;
                context.Accept(BaseOptions.Description.Dictionary);
            }

            if (PriorHandler != null)
            {
                PriorHandler.SignIn(context);
            }
        }