private async Task PerformSignIn(GenericPrincipal user, string webToken) { Dictionary <string, string> items = new Dictionary <string, string> { { "AuthScheme", CookieAuthenticationDefaults.AuthenticationScheme }, }; AuthenticationProperties props = new AuthenticationProperties(items) { // web authentication ticket life time, after expire new log in required ExpiresUtc = DateTime.UtcNow.AddHours(8), IsPersistent = false, AllowRefresh = false, }; List <AuthenticationToken> authenticationTokens = new List <AuthenticationToken> { new AuthenticationToken { Name = "access_token", Value = webToken }, }; AuthenticationTokenExtensions.StoreTokens(props, authenticationTokens); await AuthenticationHttpContextExtensions.SignInAsync(_httpContext, CookieAuthenticationDefaults.AuthenticationScheme, user, props); }
public async Task <IActionResult> ExternalLoginCallback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } var externalUser = new ExternalUser(result.Properties.Items["scheme"], result.Principal); var provider = externalUser.Provider; var userId = externalUser.UniqueIdentifier(); var user = _userRepository.GetUser(userId, provider); if (user == null) { // this sample simply auto-provisions new external user // another common approach is to start a registrations workflow first var context = _interaction.GetAuthorizationContextAsync(result.Properties.Items["returnUrl"]); var tenant = _tenantRepository.GetTenantByName(context.Result.Tenant); user = externalUser.ProvisionUser(userId, tenant.Id.ToString()); _userRepository.AddUser(user); } // if the external provider issued an id_token, we'll keep it for signout AuthenticationProperties props = null; var id_token = AuthenticationTokenExtensions.GetTokenValue(result.Properties, "id_token"); if (id_token != null) { props = new AuthenticationProperties(); props.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } // issue authentication cookie for user await _events.RaiseAsync(new UserLoginSuccessEvent(provider, userId, user.SubjectId, user.Username)); await HttpContext.SignInAsync(user.SubjectId, user.Username, provider, props, externalUser.SessionIdClaim(), user.Claims.First(x => x.Type == ClaimType.TenantId)); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); // validate return URL and redirect back to authorization endpoint or a local page var returnUrl = result.Properties.Items["returnUrl"]; if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } return(Redirect("~/")); }