public override async Task SigningOut(CookieSigningOutContext context)
        {
            var result = await context.HttpContext.AuthenticateAsync();

            if (!result.Succeeded)
            {
                _logger.LogDebug("Can't find cookie for default scheme. Might have been deleted already.");
                return;
            }

            var tokens = result.Properties.GetTokens();

            if (tokens == null || !tokens.Any())
            {
                _logger.LogDebug("No tokens found in cookie properties. SaveTokens must be enabled for automatic token revocation.");
                return;
            }

            var refreshToken = tokens.SingleOrDefault(t => t.Name == OpenIdConnectParameterNames.RefreshToken);

            if (refreshToken == null)
            {
                _logger.LogWarning("No refresh token found in cookie properties. A refresh token must be requested and SaveTokens must be enabled.");
                return;
            }

            var response = await _tokenEndpointService.RevokeTokenAsync(refreshToken.Value);

            if (response.IsError)
            {
                _logger.LogWarning("Error revoking token: {error}", response.Error);
                return;
            }
        }
Ejemplo n.º 2
0
        public override async Task SigningOut(CookieSigningOutContext context)
        {
            if (m_options.RevokeRefreshTokenOnSignout == false)
            {
                return;
            }

            var result = await context.HttpContext.AuthenticateAsync();

            if (!result.Succeeded)
            {
                return;
            }

            var tokens = result.Properties.GetTokens().ToList();

            if (!tokens.Any())
            {
                return;
            }

            var refreshToken = tokens.SingleOrDefault(t => t.Name == OpenIdConnectParameterNames.RefreshToken);

            if (refreshToken == null)
            {
                return;
            }

            var response = await m_client.RevokeTokenAsync(refreshToken.Value);
        }
Ejemplo n.º 3
0
        public override Task SigningOut(CookieSigningOutContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context cannot be null");
            }

            var userIdClaim  = context.HttpContext.User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
            var sessionClaim = context.HttpContext.User.Claims.SingleOrDefault(c => c.Type == _claimsKey);

            Guid sessionId;

            if (!Guid.TryParse(sessionClaim.Value, out sessionId))
            {
                //Log this?
            }

            var dbContext = (ApplicationDbContext)context.HttpContext.RequestServices.GetService(typeof(ApplicationDbContext));

            var sessionObject = dbContext.UserSession.SingleOrDefault(s => s.UserId == userIdClaim.Value && s.UserSessionId == sessionId);

            if (sessionObject != null)
            {
                dbContext.UserSession.Remove(sessionObject);
                dbContext.SaveChanges();
            }

            return(base.SigningOut(context));
        }
Ejemplo n.º 4
0
        private static async Task OnCookieAuthenticationSignOut(CookieSigningOutContext signOutContext)
        {
            var httpContext       = signOutContext.HttpContext;
            var user              = httpContext.User;
            var remoteAuthSchemes = (await httpContext.RequestServices
                                     .GetRequiredService <IAuthenticationSchemeProvider>()
                                     .GetRequestHandlerSchemesAsync())
                                    .ToDictionary(sch => sch.Name);
            var handlerProvider = httpContext.RequestServices
                                  .GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var identity in user.Identities)
            {
                string remoteAuthSchemeName = identity.AuthenticationType;
                if (remoteAuthSchemeName == signOutContext.Scheme.Name ||
                    !remoteAuthSchemes.TryGetValue(remoteAuthSchemeName, out var remoteAuthScheme))
                {
                    continue;
                }

                var signOutScheme = await AuthenticationSchemeSelector
                                    .ResolveSignOutScheme(remoteAuthScheme, httpContext, handlerProvider);

                if (string.IsNullOrEmpty(signOutScheme))
                {
                    continue;
                }

                await httpContext.SignOutAsync(signOutScheme, signOutContext.Properties);
            }
        }
        protected override async Task HandleSignOutAsync(SignOutContext signOutContext)
        {
            var ticket = await EnsureCookieTicket();

            var cookieOptions = BuildCookieOptions();

            if (Options.SessionStore != null && _sessionKey != null)
            {
                await Options.SessionStore.RemoveAsync(_sessionKey);
            }

            var context = new CookieSigningOutContext(
                Context,
                Options,
                cookieOptions);

            await Options.Events.SigningOut(context);

            Options.CookieManager.DeleteCookie(
                Context,
                Options.CookieName,
                context.CookieOptions);

            // Only redirect on the logout path
            var shouldRedirect = Options.LogoutPath.HasValue && OriginalPath == Options.LogoutPath;

            await ApplyHeaders(shouldRedirect);
        }
        public override async Task SigningOut(CookieSigningOutContext context)
        {
            if (!_options.RevokeRefreshTokenOnSignout)
            {
                return;
            }

            var result = await context.HttpContext.AuthenticateAsync();

            if (!result.Succeeded)
            {
                return;
            }

            var tokens = (result.Properties.GetTokens() ?? Enumerable.Empty <AuthenticationToken>()).ToArray();

            if (!tokens.Any())
            {
                return;
            }

            var refreshToken = tokens.SingleOrDefault(t => t.Name == OpenIdConnectParameterNames.RefreshToken);

            if (refreshToken == null)
            {
                return;
            }

            var response = await _service.RevokeTokenAsync(refreshToken.Value);

            if (response.IsError)
            {
                _logger.LogWarning("Error revoking token: {error}", response.Error);
            }
        }
Ejemplo n.º 7
0
        protected async override Task HandleSignOutAsync(AuthenticationProperties properties)
        {
            properties = properties ?? new AuthenticationProperties();

            _signOutCalled = true;

            // Process the request cookie to initialize members like _sessionKey.
            await EnsureCookieTicket();


            //var result = await EnsureCookieTicket();
            ////if (!result.Succeeded)
            ////{
            ////    return result;
            ////}


            var cookieOptions = BuildCookieOptions();

            if (Options.SessionStore != null && _sessionKey != null)
            {
                await Options.SessionStore.RemoveAsync(_sessionKey);
            }

            var user = Context.User;

            if (user.Identity.IsAuthenticated)
            {
                var Account = user.FindFirst("Account");

                if (Account != null)
                {
                    Options.LogOut?.Invoke(Account.Value);
                }
            }


            var context = new CookieSigningOutContext(
                Context,
                Scheme,
                Options,
                properties,
                cookieOptions);

            await Events.SigningOut(context);

            Options.CookieManager.DeleteCookie(
                Context,
                Options.Cookie.Name,
                context.CookieOptions);

            // Only redirect on the logout path
            var shouldRedirect = Options.LogoutPath.HasValue && OriginalPath == Options.LogoutPath;

            await ApplyHeaders(shouldRedirect, context.Properties);



            Logger.SignedOut(Scheme.Name);
        }
Ejemplo n.º 8
0
        public override async Task SigningOut(CookieSigningOutContext context)
        {
            _logger.LogDebug($"Before {nameof(SigningOut)}");
            await base.SigningOut(context);

            _logger.LogDebug($"After {nameof(SigningOut)}");
        }
Ejemplo n.º 9
0
 public static Task UserSigningOutAsync(CookieSigningOutContext context)
 {
     context.Options.CookieManager.DeleteCookie(
         context.HttpContext,
         UserCookieKey,
         context.CookieOptions);
     return(Task.CompletedTask);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// This will ensure any impersonation cookie is deleted when a user signs out
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task SigningOutAsync(CookieSigningOutContext context)
        {
            var cookie = new ImpersonationCookie(context.HttpContext, null);

            cookie.Delete();

            return(Task.CompletedTask);
        }
Ejemplo n.º 11
0
        public override Task SigningOut(CookieSigningOutContext context)
        {
            foreach (var cookieKey in _httpContextAccessor.HttpContext.Request.Cookies.Keys.Where(w => w.EndsWith(".auth.cookie")))
            {
                _httpContextAccessor.HttpContext.Response.Cookies.Delete(cookieKey);
            }

            return(base.SigningOut(context));
        }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Context"></param>
        /// <returns></returns>
        public Task SigningOut(CookieSigningOutContext Context)
        {
            var Account = Context.HttpContext.User.FindFirst("Account");

            if (Account != null)
            {
                UserLogout();
            }
            return(Task.CompletedTask);
        }
        protected override async Task HandleSignOutAsync(SignOutContext signOutContext)
        {
            var ticket = await EnsureCookieTicket();

            //try
            //{
            var tenantResolver = tenantResolverFactory.GetResolver();

            var cookieOptions = BuildCookieOptions();

            if (Options.SessionStore != null && _sessionKey != null)
            {
                await Options.SessionStore.RemoveAsync(_sessionKey);
            }

            var context = new CookieSigningOutContext(
                Context,
                Options,
                cookieOptions);

            await Options.Events.SigningOut(context);

            //Options.CookieManager.DeleteCookie(
            //    Context,
            //    Options.CookieName,
            //    context.CookieOptions);

            Options.CookieManager.DeleteCookie(
                Context,
                tenantResolver.ResolveCookieName(Options.CookieName),
                context.CookieOptions);

            var shouldLogoutRedirect = Options.LogoutPath.HasValue && OriginalPath == Options.LogoutPath;     //TODO: adjust


            await ApplyHeaders(shouldLogoutRedirect);

            //}
            //catch (Exception exception)
            //{
            //    var exceptionContext = new CookieExceptionContext(Context, Options,
            //        CookieExceptionContext.ExceptionLocation.SignOut, exception, ticket);

            //    await Options.Events.Exception(exceptionContext);
            //    if (exceptionContext.Rethrow)
            //    {
            //        throw;
            //    }
            //}
        }
Ejemplo n.º 14
0
        internal static Task SignOutAsync(CookieSigningOutContext context)
        {
            var id = context.HttpContext.User.Identity.Name;

            using (var df = new ApplicationUsersFactory()) {
                var usr = df.GetUser(id);
                if (usr != null)
                {
                    usr.IsLogedIn = false;
                    df.Update(usr);
                }
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 15
0
        public override async Task SigningOut(CookieSigningOutContext context)
        {
            //any persisted oidc tokens should be cleared when signing out
            try
            {
                var userId   = context.HttpContext.User.GetUserIdAsGuid();
                var siteId   = context.HttpContext.User.GetUserSiteIdAsGuid();
                var commands = context.HttpContext.RequestServices.GetRequiredService <IUserCommands>();
                await commands.DeleteTokensByProvider(siteId, userId, "OpenIdConnect");
            }
            catch { }


            await base.SigningOut(context);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 注销,引导跳转认证中心登录页面
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private static Task BuildSigningOut(CookieSigningOutContext context)
        {
            var returnUrl = new UriBuilder
            {
                Host = context.Request.Host.Host,
                Port = context.Request.Host.Port ?? 80,
            };
            var redirectUrl = new UriBuilder
            {
                Host  = "sso.cg.com",
                Path  = context.Options.LoginPath,
                Query = QueryString.Create(context.Options.ReturnUrlParameter, returnUrl.Uri.ToString()).Value
            };

            context.Response.Redirect(redirectUrl.Uri.ToString());
            return(Task.CompletedTask);
        }
        private async Task OnSigningOut(CookieSigningOutContext context)
        {
            var cookieIdValue = await context.HttpContext.GetTokenAsync(TOKEN_NAME);

            if (string.IsNullOrWhiteSpace(cookieIdValue) || !Guid.TryParse(cookieIdValue, out var cookieId))
            {
                return;
            }

            var userId = GetUserId(context.HttpContext.User);

            var db     = context.HttpContext.RequestServices.GetRequiredService <ApplicationDbContext>();
            var entity = await db.AuthenticationCookies.FirstOrDefaultAsync(c => c.UserId == userId && c.Id == cookieId);

            if (entity != null)
            {
                db.AuthenticationCookies.Remove(entity);
                await db.SaveChangesAsync();
            }
        }
Ejemplo n.º 18
0
    /// <inheritdoc />
    protected override async Task HandleSignOutAsync(AuthenticationProperties?properties)
    {
        properties = properties ?? new AuthenticationProperties();

        _signOutCalled = true;

        // Process the request cookie to initialize members like _sessionKey.
        await EnsureCookieTicket();

        var cookieOptions = BuildCookieOptions();

        if (Options.SessionStore != null && _sessionKey != null)
        {
            await Options.SessionStore.RemoveAsync(_sessionKey, Context.RequestAborted);
        }

        var context = new CookieSigningOutContext(
            Context,
            Scheme,
            Options,
            properties,
            cookieOptions);

        await Events.SigningOut(context);

        Options.CookieManager.DeleteCookie(
            Context,
            Options.Cookie.Name !,
            context.CookieOptions);

        // Only redirect on the logout path
        var shouldRedirect = Options.LogoutPath.HasValue && OriginalPath == Options.LogoutPath;

        await ApplyHeaders(shouldRedirect, context.Properties);

        Logger.AuthenticationSchemeSignedOut(Scheme.Name);
    }
Ejemplo n.º 19
0
 /// <summary>
 /// Invoked on sign out.
 /// </summary>
 /// <param name="context">The <see cref="CookieSigningOutContext"/>.</param>
 public virtual Task SigningOut(CookieSigningOutContext context) => OnSigningOut(context);
 // Implements the interface method by invoking the related delegate method.
 public override Task SigningOut(CookieSigningOutContext context)
 {
     GetLogger(context).LogCallerMethodName();
     return(base.SigningOut(context));
 }
Ejemplo n.º 21
0
 public Task SigningOut(CookieSigningOutContext context)
 {
     return(Task.FromResult(0));
 }
 public Task SigningOut(CookieSigningOutContext context)
 {
     return(Task.CompletedTask);
 }
Ejemplo n.º 23
0
 public override Task SigningOut(CookieSigningOutContext context)
 {
     return(base.SigningOut(context));
 }
Ejemplo n.º 24
0
 public override Task SigningOut(CookieSigningOutContext context)
 {
     context.Response.Redirect("/User");
     return(Task.CompletedTask);
 }