Ejemplo n.º 1
0
        public async Task <IHttpActionResult> ExternalLogin(string provider)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            string userId = await IdentityManager.Logins.GetUserIdForLoginAsync(externalLogin.LoginProvider,
                                                                                externalLogin.ProviderKey);

            bool hasRegistered = userId != null;

            if (hasRegistered)
            {
                Authentication.SignOut(Startup.ExternalCookieAuthenticationType);
                IEnumerable <Claim> claims = await ApplicationOAuthProvider.GetClaimsAsync(IdentityManager, userId);

                ClaimsIdentity oAuthIdentity = ApplicationOAuthProvider.CreateIdentity(IdentityManager, claims,
                                                                                       OAuthOptions.AuthenticationType);
                ClaimsIdentity cookieIdentity = ApplicationOAuthProvider.CreateIdentity(IdentityManager, claims,
                                                                                        CookieOptions.AuthenticationType);
                AuthenticationProperties properties = await ApplicationOAuthProvider.CreatePropertiesAsync(
                    IdentityManager, userId);

                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = ApplicationOAuthProvider.CreateIdentity(IdentityManager, claims,
                                                                                       OAuthOptions.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }