public async Task <SessionCookie> GetSessionAsync(LoginUpParty loginUpParty) { logger.ScopeTrace($"Get session, Route '{RouteBinding.Route}'."); var session = await sessionCookieRepository.GetAsync(); if (session != null) { var sessionEnabled = SessionEnabled(loginUpParty); var sessionValid = SessionValid(loginUpParty, session); logger.ScopeTrace($"User '{session.Email}' session exists, Enabled '{sessionEnabled}', Valid '{sessionValid}', User id '{session.UserId}', Session id '{session.SessionId}', Route '{RouteBinding.Route}'."); if (sessionEnabled && sessionValid) { logger.SetScopeProperty("sessionId", session.SessionId); return(session); } } else { logger.ScopeTrace("Session do not exists."); } return(null); }
private async Task <LoginUpParty> CreateLoginDocumentAsync() { Console.WriteLine("Creating login"); var loginUpParty = new LoginUpParty { Name = loginName, EnableCreateUser = true, EnableCancelLogin = false, SessionLifetime = 0, PersistentSessionLifetimeUnlimited = false, LogoutConsent = LoginUpPartyLogoutConsent.Never }; await loginUpParty.SetIdAsync(new Party.IdKey { TenantName = settings.MasterTenant, TrackName = settings.MasterTrack, PartyName = loginName }); loginUpParty.SetTenantPartitionId(); await simpleTenantRepository.SaveAsync(loginUpParty); Console.WriteLine($"Login document created and saved in Cosmos DB"); return(loginUpParty); }
private async Task <IActionResult> LogoutResponse(LoginUpParty loginUpParty, string sessionId, bool postLogoutRedirect, LogoutChoice logoutChoice) { if (postLogoutRedirect) { return(await logoutUpLogic.LogoutResponseAsync(sessionId)); } else { if (logoutChoice == LogoutChoice.Logout) { logger.ScopeTrace("Show logged out dialog."); return(View("loggedOut", new LoggedOutViewModel { CssStyle = loginUpParty.CssStyle })); } else if (logoutChoice == LogoutChoice.KeepMeLoggedIn) { logger.ScopeTrace("Show logged in dialog."); return(View("LoggedIn", new LoggedInViewModel { CssStyle = loginUpParty.CssStyle })); } else { throw new NotImplementedException(); } } }
public async Task <SessionLoginUpPartyCookie> GetSessionAsync(LoginUpParty loginUpParty) { logger.ScopeTrace(() => $"Get session, Route '{RouteBinding.Route}'."); var session = await sessionCookieRepository.GetAsync(loginUpParty); if (session != null) { var sessionEnabled = SessionEnabled(loginUpParty); var sessionValid = SessionValid(loginUpParty, session); logger.ScopeTrace(() => $"User id '{session.UserId}' session exists, Enabled '{sessionEnabled}', Valid '{sessionValid}', Session id '{session.SessionId}', Route '{RouteBinding.Route}'."); if (sessionEnabled && sessionValid) { logger.SetScopeProperty(Constants.Logs.SessionId, session.SessionId); logger.SetScopeProperty(Constants.Logs.UserId, session.UserId); logger.SetScopeProperty(Constants.Logs.Email, session.Email); return(session); } await sessionCookieRepository.DeleteAsync(loginUpParty); logger.ScopeTrace(() => $"Session deleted, Session id '{session.SessionId}'."); } else { logger.ScopeTrace(() => "Session do not exists."); } return(null); }
public async Task <bool> UpdateSessionAsync(LoginUpParty loginUpParty, DownPartySessionLink newDownPartyLink, SessionLoginUpPartyCookie session, IEnumerable <Claim> claims = null) { logger.ScopeTrace(() => $"Update session, Route '{RouteBinding.Route}'."); var sessionEnabled = SessionEnabled(loginUpParty); var sessionValid = SessionValid(loginUpParty, session); if (sessionEnabled && sessionValid) { AddDownPartyLink(session, newDownPartyLink); session.LastUpdated = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); if (claims?.Count() > 0) { session.Claims = UpdateClaims(session, claims); } await sessionCookieRepository.SaveAsync(loginUpParty, session, GetPersistentCookieExpires(loginUpParty, session.CreateTime)); logger.ScopeTrace(() => $"Session updated, Session id '{session.SessionId}'.", GetSessionScopeProperties(session)); return(true); } await sessionCookieRepository.DeleteAsync(loginUpParty); logger.ScopeTrace(() => $"Session deleted, Session id '{session.SessionId}'."); return(false); }
private async Task <List <Claim> > GetClaimsAsync(LoginUpParty party, User user, long authTime, IEnumerable <string> authMethods, string sessionId, IEnumerable <Claim> acrClaims = null) { var claims = new List <Claim>(); claims.AddClaim(JwtClaimTypes.Subject, user.UserId); claims.AddClaim(JwtClaimTypes.AuthTime, authTime.ToString()); claims.AddRange(authMethods.Select(am => new Claim(JwtClaimTypes.Amr, am))); if (acrClaims?.Count() > 0) { claims.AddRange(acrClaims); } claims.AddClaim(JwtClaimTypes.SessionId, sessionId); claims.AddClaim(JwtClaimTypes.PreferredUsername, user.Email); claims.AddClaim(JwtClaimTypes.Email, user.Email); claims.AddClaim(JwtClaimTypes.EmailVerified, user.EmailVerified.ToString().ToLower()); claims.AddClaim(Constants.JwtClaimTypes.UpParty, party.Name); claims.AddClaim(Constants.JwtClaimTypes.UpPartyType, party.Type.ToString().ToLower()); if (user.Claims?.Count() > 0) { claims.AddRange(user.Claims.ToClaimList()); } logger.ScopeTrace(() => $"Up, OIDC created JWT claims '{claims.ToFormattedString()}'", traceType: TraceTypes.Claim); var transformedClaims = await claimTransformLogic.Transform(party.ClaimTransforms?.ConvertAll(t => (ClaimTransform)t), claims); logger.ScopeTrace(() => $"Up, OIDC output JWT claims '{transformedClaims.ToFormattedString()}'", traceType: TraceTypes.Claim); return(transformedClaims); }
private async Task CreateControlClientDocmentAsync(LoginUpParty loginUpParty) { Console.WriteLine("Creating control client"); Console.Write("Add localhost test domain to enable local development [y/n] (default no): "); var addLocalhostDomain = Console.ReadKey(); Console.WriteLine(string.Empty); var controlClientRedirectUris = new List <string>(); var controlClientAllowCorsOrigins = new List <string>(); controlClientRedirectUris.AddRange(GetControlClientRedirectUris(settings.FoxIDsMasterControlClientEndpoint)); controlClientAllowCorsOrigins.Add(settings.FoxIDsMasterControlClientEndpoint.TrimEnd('/')); if (char.ToLower(addLocalhostDomain.KeyChar) == 'y') { controlClientRedirectUris.AddRange(GetControlClientRedirectUris("https://localhost:44332")); controlClientAllowCorsOrigins.Add("https://localhost:44332"); } var controlClientDownParty = new OidcDownParty { Name = controlClientName }; await controlClientDownParty.SetIdAsync(new Party.IdKey { TenantName = settings.MasterTenant, TrackName = settings.MasterTrack, PartyName = controlClientName }); controlClientDownParty.AllowUpParties = new List <UpPartyLink> { new UpPartyLink { Name = loginUpParty.Name, Type = loginUpParty.Type } }; controlClientDownParty.Client = new OidcDownClient { RedirectUris = controlClientRedirectUris, ResourceScopes = new List <OAuthDownResourceScope> { new OAuthDownResourceScope { Resource = controlApiResourceName, Scopes = new[] { controlApiResourceMasterScope, controlApiResourceTenantScope }.ToList() } }, ResponseTypes = new[] { "code" }.ToList(), Scopes = GetControlClientScopes(), RequirePkce = true, AuthorizationCodeLifetime = 30, IdTokenLifetime = 1800, // 30 minutes AccessTokenLifetime = 1800, // 30 minutes RefreshTokenLifetime = 86400, // 24 hours RefreshTokenAbsoluteLifetime = 86400, // 24 hours RefreshTokenUseOneTime = true, RefreshTokenLifetimeUnlimited = false, RequireLogoutIdTokenHint = true, }; controlClientDownParty.SetTenantPartitionId(); await simpleTenantRepository.SaveAsync(controlClientDownParty); Console.WriteLine("Control client document created and saved in Cosmos DB"); }
private async Task CreatePortalClientDocmentAsync(LoginUpParty loginUpParty) { Console.WriteLine("Creating portal client"); Console.Write("Add localhost test domain to enable local development [y/n] (default no): "); var addLocalhostDomain = Console.ReadKey(); Console.WriteLine(string.Empty); var portalClientRedirectUris = new List <string>(); portalClientRedirectUris.Add(settings.FoxIDsPortalAuthResponseEndpoint); if (char.ToLower(addLocalhostDomain.KeyChar) == 'y') { portalClientRedirectUris.Add("https://localhost:44332"); } var portalClientDownParty = new OidcDownParty(); await portalClientDownParty.SetIdAsync(new Party.IdKey { TenantName = settings.MasterTenant, TrackName = settings.MasterTrack, PartyName = portalClientName }); portalClientDownParty.AllowUpParties = new List <UpPartyLink> { new UpPartyLink { Name = loginUpParty.Name, Type = loginUpParty.Type } }; portalClientDownParty.Client = new OidcDownClient { RedirectUris = portalClientRedirectUris.ToList(), ResourceScopes = new List <OAuthDownResourceScope> { new OAuthDownResourceScope { Resource = apiResourceName, Scopes = new[] { "foxids_tenant" }.ToList() } }, ResponseTypes = new[] { "code", "id_token", "token" }.ToList(), AuthorizationCodeLifetime = 10, IdTokenLifetime = 1800, // 30 minutes AccessTokenLifetime = 1800, // 30 minutes RefreshTokenLifetime = 86400, // 24 hours RefreshTokenAbsoluteLifetime = 86400, // 24 hours RefreshTokenUseOneTime = true, RefreshTokenLifetimeUnlimited = false, RequireLogoutIdTokenHint = true, }; (var secret, var oauthClientSecret) = await CreateSecretAsync(); portalClientDownParty.Client.Secrets = new List <OAuthClientSecret> { oauthClientSecret }; portalClientDownParty.SetPartitionId(); await simpleTenantRepository.SaveAsync(portalClientDownParty); Console.WriteLine("Portal client document created and saved in Cosmos DB"); Console.WriteLine($"Portal client secret is: {secret}"); }
public async Task <IActionResult> LoginResponseUpdateSessionAsync(LoginUpParty loginUpParty, DownPartySessionLink newDownPartyLink, SessionLoginUpPartyCookie session) { if (session != null && await sessionLogic.UpdateSessionAsync(loginUpParty, newDownPartyLink, session)) { return(await loginUpLogic.LoginResponseAsync(session.Claims.ToClaimList())); } else { throw new InvalidOperationException("Session do not exist or can not be updated."); } }
private LoginUpPartyViewModel ToViewModel(LoginUpParty loginUpParty) { return(loginUpParty.Map <LoginUpPartyViewModel>(afterMap: afterMap => { afterMap.EnableSingleLogout = !loginUpParty.DisableSingleLogout; afterMap.EnableResetPassword = !loginUpParty.DisableResetPassword; if (afterMap.ClaimTransforms?.Count > 0) { afterMap.ClaimTransforms = afterMap.ClaimTransforms.MapClaimTransforms(); } })); }
private async Task <IActionResult> LogoutResponse(LoginUpParty loginUpParty, LoginUpSequenceData sequenceData, LogoutChoice logoutChoice, SessionLoginUpPartyCookie session = null) { if (logoutChoice == LogoutChoice.Logout) { await oauthRefreshTokenGrantLogic.DeleteRefreshTokenGrantsAsync(sequenceData.SessionId); if (loginUpParty.DisableSingleLogout) { await sequenceLogic.RemoveSequenceDataAsync <LoginUpSequenceData>(); return(await LogoutDoneAsync(loginUpParty, sequenceData)); } else { (var doSingleLogout, var singleLogoutSequenceData) = await singleLogoutDownLogic.InitializeSingleLogoutAsync(new UpPartyLink { Name = loginUpParty.Name, Type = loginUpParty.Type }, sequenceData.DownPartyLink, session?.DownPartyLinks, session?.Claims); if (doSingleLogout) { return(await singleLogoutDownLogic.StartSingleLogoutAsync(singleLogoutSequenceData)); } else { await sequenceLogic.RemoveSequenceDataAsync <LoginUpSequenceData>(); return(await LogoutDoneAsync(loginUpParty, sequenceData)); } } } else if (logoutChoice == LogoutChoice.KeepMeLoggedIn) { await sequenceLogic.RemoveSequenceDataAsync <LoginUpSequenceData>(); if (sequenceData.PostLogoutRedirect) { return(await logoutUpLogic.LogoutResponseAsync(sequenceData)); } else { logger.ScopeTrace("Show logged in dialog."); return(View("LoggedIn", new LoggedInViewModel { CssStyle = loginUpParty.CssStyle })); } } else { throw new NotImplementedException(); } }
public async Task CreateLoginDocumentAsync(Track mTrack) { var mLoginUpParty = new LoginUpParty { Name = loginName, EnableCreateUser = true, EnableCancelLogin = false, SessionLifetime = 36000, // 10 hours PersistentSessionLifetimeUnlimited = false, LogoutConsent = LoginUpPartyLogoutConsent.IfRequired }; await mLoginUpParty.SetIdAsync(new Party.IdKey { TenantName = RouteBinding.TenantName, TrackName = mTrack.Name, PartyName = loginName }); await tenantRepository.CreateAsync(mLoginUpParty); }
private DateTimeOffset?GetPersistentCookieExpires(LoginUpParty loginUpParty, long created) { if (loginUpParty.PersistentSessionLifetimeUnlimited.Value) { return(DateTimeOffset.FromUnixTimeSeconds(created).AddYears(settings.PersistentSessionMaxUnlimitedLifetimeYears)); } else if (loginUpParty.PersistentSessionAbsoluteLifetime > 0) { return(DateTimeOffset.FromUnixTimeSeconds(created).AddSeconds(loginUpParty.PersistentSessionAbsoluteLifetime)); } else { return(null); } }
private async Task <IActionResult> LogoutDoneAsync(LoginUpParty loginUpParty, LoginUpSequenceData sequenceData) { if (sequenceData.PostLogoutRedirect) { return(await logoutUpLogic.LogoutResponseAsync(sequenceData)); } else { loginUpParty = loginUpParty ?? await tenantRepository.GetAsync <LoginUpParty>(sequenceData.UpPartyId); logger.ScopeTrace("Show logged out dialog."); return(View("loggedOut", new LoggedOutViewModel { CssStyle = loginUpParty.CssStyle })); } }
public async Task <(SessionCookie, User)> GetAndUpdateSessionCheckUserAsync(LoginUpParty loginUpParty) { logger.ScopeTrace($"Get and update session and check user, Route '{RouteBinding.Route}'."); var session = await sessionCookieRepository.GetAsync(); if (session != null) { var sessionEnabled = SessionEnabled(loginUpParty); var sessionValid = SessionValid(loginUpParty, session); logger.ScopeTrace($"User '{session.Email}' session exists, Enabled '{sessionEnabled}', Valid '{sessionValid}', User id '{session.UserId}', Session id '{session.SessionId}', Route '{RouteBinding.Route}'."); if (sessionEnabled && sessionValid) { logger.SetScopeProperty("sessionId", session.SessionId); var id = await User.IdFormat(new User.IdKey { TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName, Email = session.Email }); var user = await tenantRepository.GetAsync <User>(id, false); if (user != null && user.UserId == session.UserId) { logger.ScopeTrace($"User '{user.Email}' found, User id '{user.UserId}'."); session.LastUpdated = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); await sessionCookieRepository.SaveAsync(session, GetPersistentCookieExpires(loginUpParty, session.CreateTime)); logger.ScopeTrace($"Session updated, Session id '{session.SessionId}'.", new Dictionary <string, string> { { "sessionId", session.SessionId } }); return(session, user); } } await sessionCookieRepository.DeleteAsync(); logger.ScopeTrace($"Session deleted, Session id '{session.SessionId}'."); } else { logger.ScopeTrace("Session do not exists."); } return(null, null); }
public bool GetRequereMfa(User user, LoginUpParty loginUpParty, LoginUpSequenceData sequenceData) { if (user.RequireMultiFactor) { return(true); } else if (loginUpParty.RequireTwoFactor) { return(true); } else if (sequenceData.Acr?.Where(v => v.Equals(Constants.Oidc.Acr.Mfa, StringComparison.Ordinal))?.Count() > 0) { return(true); } return(false); }
public async Task <SessionLoginUpPartyCookie> DeleteSessionAsync(LoginUpParty loginUpParty) { logger.ScopeTrace(() => $"Delete session, Route '{RouteBinding.Route}'."); var session = await sessionCookieRepository.GetAsync(loginUpParty); if (session != null) { await sessionCookieRepository.DeleteAsync(loginUpParty); logger.ScopeTrace(() => $"Session deleted, Session id '{session.SessionId}'."); return(session); } else { logger.ScopeTrace(() => "Session do not exists."); return(null); } }
private async Task <IActionResult> LogoutDoneAsync(LoginUpParty loginUpParty, LoginUpSequenceData sequenceData) { if (sequenceData.PostLogoutRedirect) { return(await logoutUpLogic.LogoutResponseAsync(sequenceData)); } else { loginUpParty = loginUpParty ?? await tenantRepository.GetAsync <LoginUpParty>(sequenceData.UpPartyId); securityHeaderLogic.AddImgSrc(loginUpParty.IconUrl); securityHeaderLogic.AddImgSrcFromCss(loginUpParty.Css); logger.ScopeTrace(() => "Show logged out dialog."); return(View("loggedOut", new LoggedOutViewModel { Title = loginUpParty.Title, IconUrl = loginUpParty.IconUrl, Css = loginUpParty.Css })); } }
public async Task CreateSessionAsync(LoginUpParty loginUpParty, DownPartySessionLink newDownPartyLink, long authTime, IEnumerable <Claim> claims) { if (SessionEnabled(loginUpParty)) { logger.ScopeTrace(() => $"Create session, Route '{RouteBinding.Route}'."); var session = new SessionLoginUpPartyCookie { Claims = claims.ToClaimAndValues(), }; AddDownPartyLink(session, newDownPartyLink); session.CreateTime = authTime; session.LastUpdated = authTime; await sessionCookieRepository.SaveAsync(loginUpParty, session, GetPersistentCookieExpires(loginUpParty, session.CreateTime)); logger.ScopeTrace(() => $"Session created, User id '{session.UserId}', Session id '{session.SessionId}'.", GetSessionScopeProperties(session)); } }
public async Task <IActionResult> LoginResponseAsync(LoginUpParty party, User user, long authTime, IEnumerable <string> authMethods, string sessionId) { logger.ScopeTrace("Up, Login response."); var sequenceData = await sequenceLogic.GetSequenceDataAsync <LoginUpSequenceData>(); logger.SetScopeProperty("upPartyId", sequenceData.UpPartyId); var claims = new List <Claim>(); claims.AddClaim(JwtClaimTypes.Subject, user.UserId); claims.AddClaim(JwtClaimTypes.AuthTime, authTime.ToString()); claims.AddRange(authMethods.Select(am => new Claim(JwtClaimTypes.Amr, am))); claims.AddClaim(JwtClaimTypes.SessionId, sessionId); claims.AddClaim(JwtClaimTypes.PreferredUsername, user.Email); claims.AddClaim(JwtClaimTypes.Email, user.Email); if (user.Claims?.Count() > 0) { claims.AddRange(user.Claims.ToClaimList()); } claims = await claimTransformationsLogic.Transform(party.ClaimTransformations?.ConvertAll(t => (ClaimTransformation)t), claims); logger.ScopeTrace($"Response, Down type {sequenceData.DownPartyType}."); switch (sequenceData.DownPartyType) { case PartyTypes.OAuth2: throw new NotImplementedException(); case PartyTypes.Oidc: return(await serviceProvider.GetService <OidcAuthDownLogic <OidcDownParty, OidcDownClient, OidcDownScope, OidcDownClaim> >().AuthenticationResponseAsync(sequenceData.DownPartyId, claims)); case PartyTypes.Saml2: var claimsLogic = serviceProvider.GetService <ClaimsLogic <OAuthDownClient, OAuthDownScope, OAuthDownClaim> >(); var samlClaims = await claimsLogic.FromJwtToSamlClaims(claims); samlClaims.AddClaim(Saml2ClaimTypes.NameIdFormat, NameIdentifierFormats.Email.OriginalString); return(await serviceProvider.GetService <SamlAuthnDownLogic>().AuthnResponseAsync(sequenceData.DownPartyId, claims: samlClaims)); default: throw new NotSupportedException(); } }
public async Task <LoginUpParty> CreateLoginDocumentAsync(string tenantName, string trackName) { var mLoginUpParty = new LoginUpParty { Name = loginName, EnableCreateUser = true, EnableCancelLogin = false, SessionLifetime = 36000, // 10 hours PersistentSessionLifetimeUnlimited = false, LogoutConsent = LoginUpPartyLogoutConsent.IfRequired }; await mLoginUpParty.SetIdAsync(new Party.IdKey { TenantName = tenantName?.ToLower(), TrackName = trackName, PartyName = loginName }); await tenantRepository.CreateAsync(mLoginUpParty); return(mLoginUpParty); }
public async Task <LoginUpParty> CreateMasterLoginDocumentAsync(string tenantName) { var mLoginUpParty = new LoginUpParty { Name = loginName, EnableCreateUser = false, EnableCancelLogin = false, SessionLifetime = 0, PersistentSessionLifetimeUnlimited = false, LogoutConsent = LoginUpPartyLogoutConsent.Never }; await mLoginUpParty.SetIdAsync(new Party.IdKey { TenantName = tenantName?.ToLower(), TrackName = Constants.Routes.MasterTrackName, PartyName = loginName }); await tenantRepository.CreateAsync(mLoginUpParty); return(mLoginUpParty); }
public async Task <IActionResult> LoginResponseAsync(LoginUpParty loginUpParty, DownPartySessionLink newDownPartyLink, User user, IEnumerable <string> authMethods, IEnumerable <Claim> acrClaims = null, SessionLoginUpPartyCookie session = null) { var authTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); List <Claim> claims = null; if (session != null && await sessionLogic.UpdateSessionAsync(loginUpParty, newDownPartyLink, session, acrClaims)) { claims = session.Claims.ToClaimList(); } else { var sessionId = RandomGenerator.Generate(24); claims = await GetClaimsAsync(loginUpParty, user, authTime, authMethods, sessionId, acrClaims); await sessionLogic.CreateSessionAsync(loginUpParty, newDownPartyLink, authTime, claims); } return(await loginUpLogic.LoginResponseAsync(claims)); }
public async Task <bool> UpdateSessionAsync(LoginUpParty loginUpParty, SessionCookie session) { logger.ScopeTrace($"Update session, Route '{RouteBinding.Route}'."); var sessionEnabled = SessionEnabled(loginUpParty); var sessionValid = SessionValid(loginUpParty, session); if (sessionEnabled && sessionValid) { session.LastUpdated = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); await sessionCookieRepository.SaveAsync(session, GetPersistentCookieExpires(loginUpParty, session.CreateTime)); logger.ScopeTrace($"Session updated, Session id '{session.SessionId}'.", new Dictionary <string, string> { { "sessionId", session.SessionId } }); return(true); } return(false); }
private async Task <IActionResult> LoginResponse(LoginUpParty loginUpParty, User user, SessionCookie session = null) { var authTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var authMethods = new List <string>(); authMethods.Add(IdentityConstants.AuthenticationMethodReferenceValues.Pwd); string sessionId = null; if (session != null && await sessionLogic.UpdateSessionAsync(loginUpParty, session)) { sessionId = session.SessionId; } else { sessionId = RandomGenerator.Generate(24); await sessionLogic.CreateSessionAsync(loginUpParty, user, authTime, authMethods, sessionId); } return(await loginUpLogic.LoginResponseAsync(loginUpParty, user, authTime, authMethods, sessionId)); }
private async Task <List <Claim> > GetClaimsAsync(LoginUpParty party, User user, long authTime, IEnumerable <string> authMethods, string sessionId) { var claims = new List <Claim>(); claims.AddClaim(JwtClaimTypes.Subject, user.UserId); claims.AddClaim(JwtClaimTypes.AuthTime, authTime.ToString()); claims.AddRange(authMethods.Select(am => new Claim(JwtClaimTypes.Amr, am))); claims.AddClaim(JwtClaimTypes.SessionId, sessionId); claims.AddClaim(JwtClaimTypes.PreferredUsername, user.Email); claims.AddClaim(JwtClaimTypes.Email, user.Email); claims.AddClaim(JwtClaimTypes.EmailVerified, user.EmailVerified.ToString().ToLower()); claims.AddClaim(Constants.JwtClaimTypes.UpPary, party.Name); claims.AddClaim(Constants.JwtClaimTypes.UpParyType, party.Type.ToString().ToLower()); if (user.Claims?.Count() > 0) { claims.AddRange(user.Claims.ToClaimList()); } claims = await claimTransformationsLogic.Transform(party.ClaimTransforms?.ConvertAll(t => (ClaimTransform)t), claims); return(claims); }
public async Task CreateSessionAsync(LoginUpParty loginUpParty, User user, long authTime, List <string> authMethods, string sessionId) { if (SessionEnabled(loginUpParty)) { logger.ScopeTrace($"Create session for User '{user.Email}', User id '{user.UserId}', Session id '{sessionId}', Route '{RouteBinding.Route}'."); var session = new SessionCookie { Email = user.Email, UserId = user.UserId, SessionId = sessionId }; session.CreateTime = authTime; session.LastUpdated = authTime; session.AuthMethods = authMethods; await sessionCookieRepository.SaveAsync(session, GetPersistentCookieExpires(loginUpParty, session.CreateTime)); logger.ScopeTrace($"Session created, Session id '{session.SessionId}'.", new Dictionary <string, string> { { "sessionId", session.SessionId } }); } }
private async Task <IActionResult> LoginResponseAsync(LoginUpParty loginUpParty, DownPartySessionLink newDownPartyLink, User user, SessionLoginUpPartyCookie session = null) { var authTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var authMethods = new List <string>(); authMethods.Add(IdentityConstants.AuthenticationMethodReferenceValues.Pwd); List <Claim> claims = null; if (session != null && await sessionLogic.UpdateSessionAsync(loginUpParty, newDownPartyLink, session)) { claims = session.Claims.ToClaimList(); } else { var sessionId = RandomGenerator.Generate(24); claims = await GetClaimsAsync(loginUpParty, user, authTime, authMethods, sessionId); await sessionLogic.CreateSessionAsync(loginUpParty, newDownPartyLink, authTime, claims); } return(await loginUpLogic.LoginResponseAsync(claims)); }
private bool SessionValid(LoginUpParty loginUpParty, SessionCookie session) { var created = DateTimeOffset.FromUnixTimeSeconds(session.CreateTime); var lastUpdated = DateTimeOffset.FromUnixTimeSeconds(session.LastUpdated); var now = DateTimeOffset.UtcNow; if (loginUpParty.PersistentSessionLifetimeUnlimited.Value) { return(true); } else if (created.AddSeconds(loginUpParty.PersistentSessionAbsoluteLifetime) >= now) { return(true); } else if (lastUpdated.AddSeconds(loginUpParty.SessionLifetime) >= now && created.AddSeconds(loginUpParty.SessionAbsoluteLifetime) >= now) { return(true); } else { return(false); } }
private async Task CreateLoginUpPartyAsync() { Func <string, Task> getAction = async(name) => { _ = await foxIDsApiClient.GetLoginUpPartyAsync(name); }; Func <string, Task> postAction = async(name) => { var loginUpParty = new LoginUpParty { Name = name, SessionLifetime = 3600, SessionAbsoluteLifetime = 43200, EnableCancelLogin = true, EnableCreateUser = true, LogoutConsent = LoginUpPartyLogoutConsent.IfRequired, }; await foxIDsApiClient.PostLoginUpPartyAsync(loginUpParty); }; await CreateIfNotExistsAsync(loginName, getAction, postAction); }