private ChatUser GetLoggedInUser(FormsResponseSignInContext context)
        {
            var principal = context.Request.User as ClaimsPrincipal;

            if (principal != null)
            {
                return _repository.GetLoggedInUser(principal);
            }

            return null;
        }
        public void ResponseSignIn(FormsResponseSignInContext context)
        {
            var authResult = new AuthenticationResult
            {
                Success = true
            };

            ChatUser loggedInUser = GetLoggedInUser(context);

            var principal = new ClaimsPrincipal(context.Identity);

            // Do nothing if it's authenticated
            if (principal.IsAuthenticated())
            {
                EnsurePersistentCookie(context);
                return;
            }

            ChatUser user = _repository.GetUser(principal);
            authResult.ProviderName = principal.GetIdentityProvider();

            // The user exists so add the claim
            if (user != null)
            {
                if (loggedInUser != null && user != loggedInUser)
                {
                    // Set an error message
                    authResult.Message = String.Format("This {0} account has already been linked to another user.", authResult.ProviderName);
                    authResult.Success = false;

                    // Keep the old user logged in
                    context.Identity.AddClaim(new Claim(JabbRClaimTypes.Identifier, loggedInUser.Id));
                }
                else
                {
                    // Login this user
                    AddClaim(context, user);
                }

            }
            else if (principal.HasRequiredClaims())
            {
                ChatUser targetUser = null;

                // The user doesn't exist but the claims to create the user do exist
                if (loggedInUser == null)
                {
                    // New user so add them
                    user = _membershipService.AddUser(principal);

                    targetUser = user;
                }
                else
                {
                    // If the user is logged in then link
                    _membershipService.LinkIdentity(loggedInUser, principal);

                    _repository.CommitChanges();

                    authResult.Message = String.Format("Successfully linked {0} account.", authResult.ProviderName);

                    targetUser = loggedInUser;
                }

                AddClaim(context, targetUser);
            }
            else if(!principal.HasPartialIdentity())
            {
                // A partial identity means the user needs to add more claims to login
                context.Identity.AddClaim(new Claim(JabbRClaimTypes.PartialIdentity, "true"));
            }

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true
            };

            context.Response.Cookies.Append(Constants.AuthResultCookie,
                                       JsonConvert.SerializeObject(authResult),
                                       cookieOptions);
        }
        private static void AddClaim(FormsResponseSignInContext context, ChatUser user)
        {
            // Do nothing if the user is banned
            if (user.IsBanned)
            {
                return;
            }

            // Add the jabbr id claim
            context.Identity.AddClaim(new Claim(JabbRClaimTypes.Identifier, user.Id));

            // Add the admin claim if the user is an Administrator
            if (user.IsAdmin)
            {
                context.Identity.AddClaim(new Claim(JabbRClaimTypes.Admin, "true"));
            }

            EnsurePersistentCookie(context);
        }
        private static void EnsurePersistentCookie(FormsResponseSignInContext context)
        {
            if (context.Extra == null)
            {
                context.Extra = new AuthenticationExtra();
            }

            context.Extra.IsPersistent = true;
        }
 public virtual void ResponseSignIn(FormsResponseSignInContext context)
 {
     OnResponseSignin.Invoke(context);
 }
예제 #6
0
        protected override async Task ApplyResponseGrant()
        {
            _logger.WriteVerbose("ApplyResponseGrant");
            AuthenticationResponseGrant signin = Helper.LookupSignin(Options.AuthenticationType);
            bool shouldSignin = signin != null;
            AuthenticationResponseRevoke signout = Helper.LookupSignout(Options.AuthenticationType, Options.AuthenticationMode);
            bool shouldSignout = signout != null;

            if (shouldSignin || shouldSignout || _shouldRenew)
            {
                var cookieOptions = new CookieOptions
                {
                    Domain   = Options.CookieDomain,
                    HttpOnly = Options.CookieHttpOnly,
                    Path     = Options.CookiePath ?? "/",
                };
                if (Options.CookieSecure == CookieSecureOption.SameAsRequest)
                {
                    cookieOptions.Secure = Request.IsSecure;
                }
                else
                {
                    cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always;
                }

                if (shouldSignin)
                {
                    var context = new FormsResponseSignInContext(
                        Response.Environment,
                        Options.AuthenticationType,
                        signin.Identity,
                        signin.Extra);

                    DateTimeOffset issuedUtc  = Options.SystemClock.UtcNow;
                    DateTimeOffset expiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);

                    context.Extra.IssuedUtc  = issuedUtc;
                    context.Extra.ExpiresUtc = expiresUtc;

                    Options.Provider.ResponseSignIn(context);

                    if (context.Extra.IsPersistent)
                    {
                        cookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime;
                    }

                    var    model       = new AuthenticationTicket(context.Identity, context.Extra.Properties);
                    string cookieValue = Options.TicketDataHandler.Protect(model);

                    Response.AddCookie(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }
                else if (shouldSignout)
                {
                    Response.DeleteCookie(
                        Options.CookieName,
                        cookieOptions);
                }
                else if (_shouldRenew)
                {
                    AuthenticationTicket model = await Authenticate();

                    model.Extra.IssuedUtc  = _renewIssuedUtc;
                    model.Extra.ExpiresUtc = _renewExpiresUtc;

                    string cookieValue = Options.TicketDataHandler.Protect(model);

                    if (model.Extra.IsPersistent)
                    {
                        cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime;
                    }

                    Response.AddCookie(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }

                Response.SetHeader(
                    HeaderNameCacheControl,
                    HeaderValueNoCache);

                Response.SetHeader(
                    HeaderNamePragma,
                    HeaderValueNoCache);

                Response.SetHeader(
                    HeaderNameExpires,
                    HeaderValueMinusOne);

                bool shouldLoginRedirect  = shouldSignin && !string.IsNullOrEmpty(Options.LoginPath) && string.Equals(Request.Path, Options.LoginPath, StringComparison.OrdinalIgnoreCase);
                bool shouldLogoutRedirect = shouldSignout && !string.IsNullOrEmpty(Options.LogoutPath) && string.Equals(Request.Path, Options.LogoutPath, StringComparison.OrdinalIgnoreCase);

                if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
                {
                    IDictionary <string, string[]> query = Request.GetQuery();
                    string[] redirectUri;
                    if (query.TryGetValue(Options.ReturnUrlParameter ?? FormsAuthenticationDefaults.ReturnUrlParameter, out redirectUri) &&
                        redirectUri != null &&
                        redirectUri.Length == 1 &&
                        IsHostRelative(redirectUri[0]))
                    {
                        Response.Redirect(redirectUri[0]);
                    }
                }
            }
        }
        protected override async Task ApplyResponseGrant()
        {
            var signin        = Helper.LookupSignin(Options.AuthenticationType);
            var shouldSignin  = signin != null;
            var signout       = Helper.LookupSignout(Options.AuthenticationType, Options.AuthenticationMode);
            var shouldSignout = signout != null;

            if (shouldSignin || shouldSignout || _shouldRenew)
            {
                var cookieOptions = new CookieOptions
                {
                    Domain   = Options.CookieDomain,
                    HttpOnly = Options.CookieHttpOnly,
                    Path     = Options.CookiePath ?? "/",
                    Secure   = Options.CookieSecure,
                };

                if (shouldSignin)
                {
                    var context = new FormsResponseSignInContext(
                        Response.Environment,
                        Options.AuthenticationType,
                        signin.Identity,
                        signin.Extra);

                    var issuedUtc  = DateTimeOffset.UtcNow;
                    var expiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);

                    context.Extra.IssuedUtc  = issuedUtc;
                    context.Extra.ExpiresUtc = expiresUtc;

                    Options.Provider.ResponseSignIn(context);

                    if (context.Extra.IsPersistent)
                    {
                        cookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime;
                    }

                    var model       = new AuthenticationTicket(context.Identity, context.Extra.Properties);
                    var cookieValue = Options.TicketDataHandler.Protect(model);

                    Response.AddCookie(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }
                else if (shouldSignout)
                {
                    Response.DeleteCookie(
                        Options.CookieName,
                        cookieOptions);
                }
                else if (_shouldRenew)
                {
                    var model = await Authenticate();

                    model.Extra.IssuedUtc  = _renewIssuedUtc;
                    model.Extra.ExpiresUtc = _renewExpiresUtc;

                    var cookieValue = Options.TicketDataHandler.Protect(model);

                    if (model.Extra.IsPersistent)
                    {
                        cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime;
                    }

                    Response.AddCookie(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }

                bool shouldLoginRedirect  = shouldSignin && !string.IsNullOrEmpty(Options.LoginPath) && string.Equals(Request.Path, Options.LoginPath, StringComparison.OrdinalIgnoreCase);
                bool shouldLogoutRedirect = shouldSignout && !string.IsNullOrEmpty(Options.LogoutPath) && string.Equals(Request.Path, Options.LogoutPath, StringComparison.OrdinalIgnoreCase);

                if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
                {
                    IDictionary <string, string[]> query = Request.GetQuery();
                    string[] redirectUri;
                    if (query.TryGetValue(Options.ReturnUrlParameter ?? Constants.DefaultReturnUrlParameter, out redirectUri) &&
                        redirectUri != null &&
                        redirectUri.Length == 1)
                    {
                        // TODO: safe redirect rules
                        Response.Redirect(redirectUri[0]);
                    }
                }
            }
        }
        private static void EnsurePersistentCookie(FormsResponseSignInContext context)
        {
            if (context.Extra == null)
            {
                context.Extra = new Dictionary<string, string>();
            }

            context.Extra[".persistent"] = "";
        }
예제 #9
0
 public virtual void ResponseSignIn(FormsResponseSignInContext context)
 {
     OnResponseSignin.Invoke(context);
 }