public static async Task OnSignedIn(CookieSignedInContext context) { var userRepository = context.HttpContext.RequestServices.GetService <IUserRepository>(); var user = new User { Name = context.Principal.Identity.Name }; if (await userRepository.UserExists(user.Name)) { return; } foreach (var claim in context.Principal.Claims) { switch (claim.Type) { case ClaimTypes.NameIdentifier: user.NameIdentifier = claim.Value; break; case ClaimTypes.Email: user.Email = claim.Value; break; case GitHubAuthenticationConstants.Claims.Name: user.GitHubName = claim.Value; break; } } await userRepository.Add(user); }
public override async Task SignedIn(CookieSignedInContext context) { _logger.LogDebug($"Before {nameof(SignedIn)}"); await base.SignedIn(context); _logger.LogDebug($"After {nameof(SignedIn)}"); }
public static async Task SignIn(CookieSignedInContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } string steamId = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value[SteamIdStartIndex..]; var usersRepository = context.HttpContext.RequestServices.GetRequiredService <UsersRepository>(); UserModel user = await usersRepository.GetUserAsync(steamId); if (user != null) { return; } var steamFactory = context.HttpContext.RequestServices.GetRequiredService <SteamWebInterfaceFactory>(); var httpClientFactory = context.HttpContext.RequestServices.GetRequiredService <IHttpClientFactory>(); var logger = context.HttpContext.RequestServices.GetRequiredService <ILogger <ValidationHelper> >(); var client = httpClientFactory.CreateClient(); client.Timeout = TimeSpan.FromSeconds(3); PlayerSummaryModel playerSummary = null; try { var response = await steamFactory.CreateSteamWebInterface <SteamUser>(client).GetPlayerSummaryAsync(ulong.Parse(steamId)); playerSummary = response.Data; } catch (Exception e) { logger.LogError(e, "An exception occurated when downloading player summaries"); } user = new UserModel() { SteamId = steamId, Role = RoleConstants.DefaultRoleId }; if (playerSummary != null) { user.Name = playerSummary.Nickname; } user = await usersRepository.AddUserAsync(user); if (playerSummary != null) { var avatar = await client.GetByteArrayAsync(playerSummary.AvatarFullUrl); await usersRepository.UpdateUserAvatarAsync(user.Id, avatar); } }
public override Task SignedIn(CookieSignedInContext context) { var decryptedCookieInfo = new AuthTokenDecryptor().DecryptAuthCookieFrom(context.Response, context.Options); var escapedDecryptedCookieInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(decryptedCookieInfo)); context.Response.Cookies.Append($"ORIGINAL_SIGNIN_STS_TOKEN_BASE64", escapedDecryptedCookieInfo, new CookieOptions { Expires = DateTime.UtcNow.AddSeconds(1) }); return(base.SignedIn(context)); }
/// <summary> /// /// </summary> /// <param name="Context"></param> /// <returns></returns> public Task SignedInFun(CookieSignedInContext Context) { var Account = Context.Principal.FindFirst("Account"); if (Account != null) { UserLogin(Account.Value); } return(Task.CompletedTask); }
public override Task SignedIn(CookieSignedInContext context) { var usernameClaim = context.Principal.FindFirst("preferred_username").Value; if (!_context.Users.Any(u => u.Username.Equals(usernameClaim))) { User user = new User(); user.Username = usernameClaim; _context.Users.Add(user); _context.SaveChanges(); } return(base.SignedIn(context)); }
/// <summary> /// Serialized some attributes about the current user for our web app to work /// </summary> public static async Task UserSignedInAsync(CookieSignedInContext context) { if (context.HttpContext.RequestServices == null) { throw new InvalidOperationException("RequestServices is null."); } var userManager = context.HttpContext.RequestServices.GetRequiredService <UserManager <User> >(); var service = context.HttpContext.RequestServices.GetRequiredService <IUserManagementService>(); var user = await userManager.GetUserAsync(context.Principal); if (user == null) { throw new InvalidOperationException("Cannot get user from cookie context."); } var roles = await userManager.GetRolesAsync(user); var isAdmin = await service.IsAdminAsync(roles); var userCookie = new UserCookie(user.UserName, isAdmin); var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var builtCookie = JsonSerializer.Serialize <UserCookie>(userCookie, serializeOptions); var builder = new CookieBuilder { HttpOnly = false, IsEssential = true, Expiration = context.Options.ExpireTimeSpan }; var cookie = builder.Build(context.HttpContext); context.Options.CookieManager.AppendResponseCookie( context.HttpContext, UserCookieKey, builtCookie, cookie); }
public override async Task SignedIn(CookieSignedInContext context) { var logger = _loggerFactory.CreateLogger("MyCookieAuthenticationEvents"); logger.LogInformation("Entering SignedIn Event"); string name = context.Principal.Identity.Name; Claim subClaim = context.Principal.Claims.First(c => c.Type == "sub"); OIDCUser user = await _dbContext.OIDCUsers.FirstOrDefaultAsync(u => u.Subject == subClaim.Value); if (user == null) { logger.LogInformation("Creating user"); _dbContext.OIDCUsers.Add(new OIDCUser() { Name = name, Subject = subClaim.Value }); await _dbContext.SaveChangesAsync(); } else { logger.LogInformation("User already created"); } }
/// <summary> /// Invoked after sign in has completed. /// </summary> /// <param name="context">The <see cref="CookieSignedInContext"/>.</param> public virtual Task SignedIn(CookieSignedInContext context) => OnSignedIn(context);
// Implements the interface method by invoking the related delegate method. public override Task SignedIn(CookieSignedInContext context) { GetLogger(context).LogCallerMethodName(); return(base.SignedIn(context)); }
public override Task SignedIn(CookieSignedInContext context) { return(base.SignedIn(context)); }
public override Task SignedIn(CookieSignedInContext context) { return(Task.CompletedTask); }
private async Task OnSignedIn(CookieSignedInContext ctx) { var userJson = ctx.HttpContext.Items["User"]; var steamId = ctx.Principal.GetSteamId(); var steamApiKey = Configuration.GetSection("Steam").GetSection("ApiKey").Value; var url = $"https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={steamApiKey}&steamids={steamId}"; if (userJson == null) { userJson = await new HttpClient().GetStringAsync(url); } DatabaseModel.User user; try { var res = new Regex(@"(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/|\.jpg)") .Replace(userJson.ToString(), ""); user = SteamPlayerMapping.GetUserFromSteamObject(res); } catch (Exception e) { throw new InvalidJsonFromSteamException("Can't convert from steamJsonPlayer data to a user", e); } if (steamId != user.SteamId) { throw new ArgumentException("SteamId is not the same!"); } var firstTimeUser = await IoC.Container.Resolve <IUserService>().UserLoggedIn(user); if (firstTimeUser) { UserValidationResult userValidationResult = new UserValidationResult { Error = "Unknown error", ShouldReviceItems = false }; try { var playerInfo = await IoC.Container.Resolve <ISteamService>().GetPlayerInfoAsync(user.SteamId); userValidationResult = new UserValidationResult(userJson.ToString(), playerInfo); if (userValidationResult.ShouldReviceItems) { var userToSendFrom = await IoC.Container.Resolve <IUserService>().FindAsync(Constants.OurRandomSteamId); var itemToSend = await GetItemToSend(userToSendFrom); if (itemToSend.Count != 0) { await SendItems(user, itemToSend, userToSendFrom); } else { userValidationResult.Error = "Out of items"; userValidationResult.ShouldReviceItems = false; } } } catch (Exception e) { Console.WriteLine(e); } var redirectUrl = $"{ctx.Request.Scheme}://{ctx.Request.Host.Host}/coinflip/create?success={userValidationResult.ShouldReviceItems.ToString()}&reason={userValidationResult.Error}"; ctx.Response.Redirect(redirectUrl); var ste = ctx.HttpContext.Response.Body; var s = new StreamWriter(ste); await s.WriteAsync(""); await s.FlushAsync(); ctx.Response.Body = ste; } }
public override Task SignedIn(CookieSignedInContext context) { return(_options.CookieEvents.SignedIn(context)); }
protected override async Task HandleSignInAsync(SignInContext signin) { var ticket = await EnsureCookieTicket(signin is WsFedSignInContext); var cookieOptions = BuildCookieOptions(); var signInContext = new CookieSigningInContext( Context, Options, Options.AuthenticationScheme, signin.Principal, new AuthenticationProperties(signin.Properties), cookieOptions); DateTimeOffset issuedUtc; if (signInContext.Properties.IssuedUtc.HasValue) { issuedUtc = signInContext.Properties.IssuedUtc.Value; } else { issuedUtc = Options.SystemClock.UtcNow; signInContext.Properties.IssuedUtc = issuedUtc; } if (!signInContext.Properties.ExpiresUtc.HasValue) { signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan); } await Options.Events.SigningIn(signInContext); if (signInContext.Properties.IsPersistent) { var expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan); signInContext.CookieOptions.Expires = DateTime.SpecifyKind(expiresUtc.ToUniversalTime().DateTime, DateTimeKind.Utc); } ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.AuthenticationScheme); if (Options.SessionStore != null) { if (_sessionKey != null) { await Options.SessionStore.RemoveAsync(_sessionKey); } _sessionKey = await Options.SessionStore.StoreAsync(ticket); var principal = new ClaimsPrincipal( new ClaimsIdentity( new[] { new Claim(SessionIdClaim, _sessionKey, ClaimValueTypes.String, Options.ClaimsIssuer) }, Options.ClaimsIssuer)); ticket = new AuthenticationTicket(principal, null, Options.AuthenticationScheme); } var cookieValue = Options.TicketDataFormat.Protect(ticket, GetTlsTokenBinding()); Options.CookieManager.AppendResponseCookie( Context, Options.CookieName, cookieValue, signInContext.CookieOptions); var signedInContext = new CookieSignedInContext( Context, Options, Options.AuthenticationScheme, signInContext.Principal, signInContext.Properties); await Options.Events.SignedIn(signedInContext); //should always redirect for WsFed - well for passive anyway. string returnUrl = null; if (signin is WsFedSignInContext) { returnUrl = (signin as WsFedSignInContext).ReturnUrl; } await ApplyHeaders(true, returnUrl); }
internal static Task SignInAsync(CookieSignedInContext context) { return(Task.CompletedTask); }
protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) { if (user == null) { throw new ArgumentNullException(nameof(user)); } properties = properties ?? new AuthenticationProperties(); _signInCalled = true; // Process the request cookie to initialize members like _sessionKey. await EnsureCookieTicket(); var cookieOptions = BuildCookieOptions(); var signInContext = new CookieSigningInContext( Context, Scheme, Options, user, properties, cookieOptions); DateTimeOffset issuedUtc; if (signInContext.Properties.IssuedUtc.HasValue) { issuedUtc = signInContext.Properties.IssuedUtc.Value; } else { issuedUtc = Clock.UtcNow; signInContext.Properties.IssuedUtc = issuedUtc; } if (!signInContext.Properties.ExpiresUtc.HasValue) { signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan); } await Events.SigningIn(signInContext); if (signInContext.Properties.IsPersistent) { var expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan); signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime(); } var ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.Scheme.Name); if (Options.SessionStore != null) { if (_sessionKey != null) { await Options.SessionStore.RemoveAsync(_sessionKey); } _sessionKey = await Options.SessionStore.StoreAsync(ticket); var principal = new ClaimsPrincipal( new ClaimsIdentity( new[] { new Claim(SessionIdClaim, _sessionKey, ClaimValueTypes.String, Options.ClaimsIssuer) }, Options.ClaimsIssuer)); ticket = new AuthenticationTicket(principal, null, Scheme.Name); } var cookieValue = Options.TicketDataFormat.Protect(ticket); Options.CookieManager.AppendResponseCookie( Context, Options.Cookie.Name, cookieValue, signInContext.CookieOptions); var signedInContext = new CookieSignedInContext( Context, Scheme, signInContext.Principal, signInContext.Properties, Options); await Events.SignedIn(signedInContext); // Only redirect on the login path var shouldRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath; await ApplyHeaders(shouldRedirect, signedInContext.Properties); Logger.SignedIn(Scheme.Name); }
public override Task SignedIn(CookieSignedInContext context) { context.Properties.IsPersistent = true; return(base.SignedIn(context)); }
protected override async Task HandleSignInAsync(SignInContext signin) { var ticket = await EnsureCookieTicket(); //try //{ var tenantResolver = tenantResolverFactory.GetResolver(); var cookieOptions = BuildCookieOptions(); //var signInContext = new CookieResponseSignInContext( // Context, // Options, // Options.AuthenticationScheme, // signin.Principal, // new AuthenticationProperties(signin.Properties), // cookieOptions); var signInContext = new CookieSigningInContext( Context, Options, tenantResolver.ResolveAuthScheme(Options.AuthenticationScheme), signin.Principal, new AuthenticationProperties(signin.Properties), cookieOptions); DateTimeOffset issuedUtc; if (signInContext.Properties.IssuedUtc.HasValue) { issuedUtc = signInContext.Properties.IssuedUtc.Value; } else { issuedUtc = Options.SystemClock.UtcNow; signInContext.Properties.IssuedUtc = issuedUtc; } if (!signInContext.Properties.ExpiresUtc.HasValue) { signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan); } await Options.Events.SigningIn(signInContext); if (signInContext.Properties.IsPersistent) { var expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan); signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime; } ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.AuthenticationScheme); if (Options.SessionStore != null) { if (_sessionKey != null) { await Options.SessionStore.RemoveAsync(_sessionKey); } _sessionKey = await Options.SessionStore.StoreAsync(ticket); var principal = new ClaimsPrincipal( new ClaimsIdentity( new[] { new Claim(SessionIdClaim, _sessionKey, ClaimValueTypes.String, Options.ClaimsIssuer) }, Options.ClaimsIssuer)); //ticket = new AuthenticationTicket(principal, null, Options.AuthenticationScheme); ticket = new AuthenticationTicket(principal, null, tenantResolver.ResolveAuthScheme(Options.AuthenticationScheme)); } //var cookieValue = Options.TicketDataFormat.Protect(ticket); var ticketDataFormet = GetTicketDataFormat(tenantResolver); var cookieValue = ticketDataFormet.Protect(ticket); //Options.CookieManager.AppendResponseCookie( // Context, // Options.CookieName, // cookieValue, // signInContext.CookieOptions); Options.CookieManager.AppendResponseCookie( Context, tenantResolver.ResolveCookieName(Options.CookieName), cookieValue, signInContext.CookieOptions); //var signedInContext = new CookieResponseSignedInContext( // Context, // Options, // Options.AuthenticationScheme, // signInContext.Principal, // signInContext.Properties); var signedInContext = new CookieSignedInContext( Context, Options, tenantResolver.ResolveAuthScheme(Options.AuthenticationScheme), signInContext.Principal, signInContext.Properties); await Options.Events.SignedIn(signedInContext); var shouldLoginRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath; await ApplyHeaders(shouldLoginRedirect); //} //catch (Exception exception) //{ // var exceptionContext = new CookieExceptionContext(Context, Options, // CookieExceptionContext.ExceptionLocation.SignIn, exception, ticket); // await Options.Events.Exception(exceptionContext); // if (exceptionContext.Rethrow) // { // throw; // } //} }
public Task SignedIn(CookieSignedInContext context) { return(Task.FromResult(0)); }