Ejemplo n.º 1
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

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

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

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                 externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
        public async Task <IHttpActionResult> Login(LoginInfoModel loginInfo)
        {
            if (!User.Identity.IsAuthenticated)
            {
                var user = await UserManager.FindAsync(loginInfo.Email, loginInfo.Password);

                ClaimsIdentity userIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);

                Authentication.SignIn(properties, userIdentity, cookieIdentity);
            }

            return(Ok());
        }
Ejemplo n.º 3
0
        private async Task <AuthenticationProperties> CreateInitialRefreshToken(string clientId, ApplicationUser user, ClaimsIdentity oAuthIdentity)
        {
            var userOrganization = new UserAndOrganizationDto
            {
                OrganizationId = user.OrganizationId,
                UserId         = user.Id
            };

            await _refreshTokenService.RemoveTokenBySubjectAsync(userOrganization);

            var properties = ApplicationOAuthProvider.CreateProperties(user.Id, clientId);

            var ticket  = new AuthenticationTicket(oAuthIdentity, properties);
            var context = new AuthenticationTokenCreateContext(Request.GetOwinContext(), Startup.OAuthServerOptions.RefreshTokenFormat, ticket);

            await Startup.OAuthServerOptions.RefreshTokenProvider.CreateAsync(context);

            properties.Dictionary.Add("refresh_token", context.Token);
            return(properties);
        }
        public async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
        {
            // Clear any partial cookies from external or two factor partial sign ins
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);

            var oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager);

            var cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType);

            var properties = ApplicationOAuthProvider.CreateProperties(user.UserName, isPersistent);

            if (rememberBrowser)
            {
                var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(user.Id);
                AuthenticationManager.SignIn(properties, oAuthIdentity, cookieIdentity, rememberBrowserIdentity);
            }
            else
            {
                AuthenticationManager.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
        }
Ejemplo n.º 5
0
        public async Task <IHttpActionResult> Login(LoginViewModel loginVM)
        {
            ApplicationUser user = UserManager.Find(loginVM.Username, loginVM.Password);

            if (user != null)
            {
                if (!user.EmailConfirmed)
                {
                    ModelState.AddModelError("", "Niste aktivirali profil");
                    return(BadRequest(ModelState));
                }

                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
                try
                {
                    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                        OAuthDefaults.AuthenticationType);

                    ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                         CookieAuthenticationDefaults.AuthenticationType);

                    var role   = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).FirstOrDefault().Value;
                    var userId = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
                    AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName, role, userId);
                    Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                    return(Ok(properties.Dictionary));
                }
                catch (Exception)
                {
                    return(BadRequest());
                }
            }
            else
            {
                ModelState.AddModelError("", "Ne postoji korisnik sa unetim Email-om i šifrom");
                return(BadRequest(ModelState));
            }
        }
Ejemplo n.º 6
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

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

            if (externalLogin == null || externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
                return(Redirect(Url.Content("~/")));
            }

            IdentityAccount account = await _userManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

            if (account == null)
            {
                IdentityResult result = null;

                account = await _userManager.FindByNameAsync(externalLogin.UserName);

                if (account == null)
                {
                    account = new IdentityAccount {
                        UserName = externalLogin.UserName
                    };
                    result = await _userManager.CreateAsync(account);

                    if (!result.Succeeded)
                    {
                        return(InternalServerError());
                    }
                }

                UserLoginInfo login = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);
                result = await _userManager.AddLoginAsync(account.Id, login);

                if (!result.Succeeded)
                {
                    return(InternalServerError());
                }
            }

            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            ClaimsIdentity oAuthIdentity = await _userManager.CreateIdentityAsync(account,
                                                                                  OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookieIdentity = await _userManager.CreateIdentityAsync(account,
                                                                                   CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(account.UserName);

            Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

            return(Ok());
        }
Ejemplo n.º 7
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

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

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

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            var user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                SignInManager.SignOut();
                //Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                SignInManager.SignIn(user, false, false);
                //Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);

                var userInfo = UserManager2.CreateUserInfo("", externalLogin.UserName, "", "", "");

                user = new User()
                {
                    UserName      = externalLogin.UserName,
                    PasswordHash  = null,
                    IsActive      = true,
                    UserType      = (int)UserTypeEnum.Client,
                    UserInfoId    = userInfo.Id,
                    AccountPlanId = (int)AccountPlanEnum.Start,
                    Registration  = DateTime.Now,
                    LastUpdate    = DateTime.Now
                };

                IdentityResult result = await UserManager.CreateAsync(user);

                IdentityResult loginResult = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

                SignInManager.SignIn(user, false, false);
                //Authentication.SignIn(identity);
            }

            return(Ok());
        }
Ejemplo n.º 8
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            string redirectUri = string.Empty;

            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

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

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

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }
            var redirectUriValidationResult = ValidateClientAndRedirectUri(this.Request, ref redirectUri);

            if (!string.IsNullOrWhiteSpace(redirectUriValidationResult))
            {
                return(BadRequest(redirectUriValidationResult));
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                 externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            //redirectUri = string.Format("{0}#external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}",
            //                                redirectUri,
            //                                externalLogin.ExternalAccessToken,
            //                                externalLogin.LoginProvider,
            //                                hasRegistered.ToString(),
            //                                externalLogin.UserName);

            redirectUri = string.Format("{0}#external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}",
                                        redirectUri,
                                        externalLogin.ExternalAccessToken,
                                        externalLogin.LoginProvider,
                                        hasRegistered.ToString(),
                                        externalLogin.UserName);

            return(Redirect(redirectUri));
        }
Ejemplo n.º 9
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (result?.Identity == null)
            {
                return(RedirectToAction("Login"));
            }

            var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);

            if (idClaim == null)
            {
                return(RedirectToAction("Login"));
            }

            var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);

            // Sign in the user with this external login provider if the user already has a login
            ApplicationUser user = await UserManager.FindAsync(login);

            if (user != null)
            {
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                user.LastConsent = DateTime.UtcNow;
                await UserManager.UpdateAsync(user);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                RegisterExternalBindingModel model = new RegisterExternalBindingModel();

                if (idClaim.Issuer == "Facebook")
                {
                    // Get details from Facebook
                    var accessToken   = result.Identity.Claims.Where(c => c.Type.Equals("ExternalAccessToken")).Select(c => c.Value).FirstOrDefault();
                    Uri apiRequestUri = new Uri("https://graph.facebook.com/me?fields=id,first_name,last_name,email,picture.type(square)&access_token=" + accessToken);

                    using (var webClient = new WebClient())
                    {
                        var     json       = webClient.DownloadString(apiRequestUri);
                        dynamic jsonResult = JsonConvert.DeserializeObject(json);
                        model.Email       = jsonResult.email;
                        model.Given_name  = jsonResult.first_name;
                        model.Family_name = jsonResult.last_name;
                        model.Picture     = jsonResult.picture.data.url;
                    }
                }
                else
                {
                    // Get details from Google
                    var accessToken   = result.Identity.Claims.Where(c => c.Type.Equals("urn:google:accesstoken")).Select(c => c.Value).FirstOrDefault();
                    Uri apiRequestUri = new Uri("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + accessToken);

                    using (var webClient = new WebClient())
                    {
                        var     json       = webClient.DownloadString(apiRequestUri);
                        dynamic jsonResult = JsonConvert.DeserializeObject(json);
                        model.Email       = jsonResult.email;
                        model.Picture     = jsonResult.picture;
                        model.Family_name = jsonResult.family_name;
                        model.Given_name  = jsonResult.given_name;
                    }
                }

                var appUser = new ApplicationUser
                {
                    UserName     = model.Email,
                    Email        = model.Email,
                    ImageUrl     = model.Picture,
                    FirstName    = model.Given_name,
                    Surname      = model.Family_name,
                    DateCreated  = DateTime.UtcNow,
                    AuthProvider = idClaim.Issuer,
                    Trusted      = false,
                    LastConsent  = DateTime.UtcNow
                };

                ApplicationUser existingResult = await UserManager.FindByEmailAsync(appUser.Email);

                if (existingResult == null)
                {
                    // New user
                    IdentityResult createResult = await UserManager.CreateAsync(appUser);

                    if (!createResult.Succeeded)
                    {
                        return(RedirectToAction("Login"));
                    }
                }
                else
                {
                    // user already exists with that email
                    appUser = existingResult;
                }

                // Add this oauth login to the user account
                IdentityResult idResult = await UserManager.AddLoginAsync(appUser.Id, login);

                if (!idResult.Succeeded)
                {
                    return(RedirectToAction("Login"));
                }

                ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(UserManager,
                                                                                       OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await appUser.GenerateUserIdentityAsync(UserManager,
                                                                                        CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(appUser.UserName);
                await SignInManager.SignInAsync(appUser, true, true);

                Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                return(RedirectToLocal(returnUrl));
            }
        }
Ejemplo n.º 10
0
        public async Task <ActionResult> HandleResponseFromApple(InitialTokenResponse response)
        {
            try
            {
                // TODO should probably check state here but MVC seems to have different session IDs for each request yay

                // Create a new instance of AppleAuthProvider
                AppleAuthProvider provider = new AppleAuthProvider(
                    ConfigurationManager.AppSettings["oauth:apple:id"],
                    ConfigurationManager.AppSettings["oauth:apple:teamid"],
                    ConfigurationManager.AppSettings["oauth:apple:keyid"],
                    string.Format("https://{0}/account/HandleResponseFromApple", Request.Url.Authority),
                    Session.SessionID);
                // Retrieve an authorization token
                AuthorizationToken authorizationToken = await provider.GetAuthorizationToken(response.code, ConfigurationManager.AppSettings["oauth:apple:secret"]);

                var             login = new UserLoginInfo("Apple", authorizationToken.UserInformation.UserID);
                ApplicationUser user  = await UserManager.FindAsync(login);

                // apple only returns the user's details on the first authentication
                if (user == null && !string.IsNullOrWhiteSpace(response.user))
                {
                    dynamic appleUser = JsonConvert.DeserializeObject(response.user);

                    ApplicationUser appUser = new ApplicationUser
                    {
                        UserName     = appleUser.email,
                        Email        = appleUser.email,
                        FirstName    = appleUser.name.firstName,
                        Surname      = appleUser.name.lastName,
                        DateCreated  = DateTime.UtcNow,
                        AuthProvider = "Apple",
                        Trusted      = false,
                        LastConsent  = DateTime.UtcNow
                    };

                    ApplicationUser existingResult = await UserManager.FindByEmailAsync(appUser.Email);

                    if (existingResult == null)
                    {
                        // New user
                        IdentityResult createResult = await UserManager.CreateAsync(appUser);

                        if (!createResult.Succeeded)
                        {
                            return(RedirectToAction("Login"));
                        }
                    }
                    else
                    {
                        // user already exists with that email
                        appUser = existingResult;
                    }

                    // Add this oauth login to the user account
                    IdentityResult idResult = await UserManager.AddLoginAsync(appUser.Id, login);

                    if (!idResult.Succeeded)
                    {
                        return(RedirectToAction("Login"));
                    }

                    ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(UserManager,
                                                                                           OAuthDefaults.AuthenticationType);

                    ClaimsIdentity cookieIdentity = await appUser.GenerateUserIdentityAsync(UserManager,
                                                                                            CookieAuthenticationDefaults.AuthenticationType);

                    AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(appUser.UserName);
                    await SignInManager.SignInAsync(appUser, true, true);

                    Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                    return(RedirectToLocal("/"));
                }
                else if (user != null)
                {
                    // existing user
                    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);

                    ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType);

                    AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                    Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                    user.LastConsent = DateTime.UtcNow;
                    await UserManager.UpdateAsync(user);

                    return(RedirectToLocal("/"));
                }
                else
                {
                    // new user but apple didn't give details
                    // TODO show instructions for removing ourplace from your apple account so that it can be re-added
                    ViewData["errormessage"] = "Something went wrong while getting your details from Apple. Please remove OurPlace from your 'Sign in with Apple' security settings and try again.";
                    return(View("Error"));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                ViewData["errormessage"] = string.Format("HandleResponseFromApple\nkey{2}\n{0}\n{1}", e.Message, e.StackTrace, ConfigurationManager.AppSettings["oauth:apple:secret"]);
                return(View("Error"));
            }
        }
Ejemplo n.º 11
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

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

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

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            var loginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);

            ISofAUser user = await UserManager.FindAsync(loginInfo);

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                var info = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);

                user = new ISofAUser()
                {
                    UserName = (User.Identity as ClaimsIdentity).FindFirstValue(ClaimTypes.Name), Email = (User.Identity as ClaimsIdentity).FindFirstValue(ClaimTypes.Email)
                };

                IdentityResult result = await UserManager.CreateAsync(user);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }

                result = await UserManager.AddLoginAsync(user.Id, loginInfo);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
            }

            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                 CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user);

            Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

            return(Ok());
        }
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

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

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

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                 externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            var    otheruser         = Request.GetOwinContext().Authentication.User;
            string googleAccessToken = null;

            if (otheruser.Claims.Any(cl => cl.Type.ToLower().Contains("emailaddress")))
            {
                using (var appdbcontext = new ApplicationDbContext())
                {
                    var userEmail = otheruser.Claims.First(cl => cl.Type.ToLower().Contains("emailaddress")).Value;
                    var googleExternalLoginData = appdbcontext.ExternalLoginDatas.FirstOrDefault(eld => eld.Type == "GoogleAccessToken" && eld.Key == userEmail);

                    googleAccessToken = googleExternalLoginData.Value;
                }
            }
            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                if (!string.IsNullOrEmpty(googleAccessToken))
                {
                    oAuthIdentity.AddClaim(new Claim("GoogleAccessToken", googleAccessToken));
                }
                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                if (!string.IsNullOrEmpty(googleAccessToken))
                {
                    cookieIdentity.AddClaim(new Claim("GoogleAccessToken", googleAccessToken));
                }

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                if (!string.IsNullOrEmpty(googleAccessToken))
                {
                    identity.AddClaim(new Claim("GoogleAccessToken", googleAccessToken));
                }
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
Ejemplo n.º 13
0
        public async Task <IHttpActionResult> GetGitHubToken(string githubCode)
        {
            var    config         = GitHubAuthorizationConfiguration.CreateDefault();
            string responseString = "";

            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("Accept", "application/json");
                responseString = webClient.UploadString(config.GetTokenEndpoint(), config.GetTokenEndpointParameters(githubCode));
            }

            var responseDefiniton = new { token_type = "", scope = "", access_token = "" };
            var response          = JsonConvert.DeserializeAnonymousType(responseString, responseDefiniton);

            var accessToken = response.access_token;

            string userInformationString = "";

            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("Accept", "application/json");
                // Set a User-Agent ... any User-Agent..... , otherwise receive a 403 Unauthorized.... yup!
                webClient.Headers.Add("User-Agent", "Y U require this header, github? this cost me some 30 minutes!");
                userInformationString = webClient.DownloadString(string.Format("https://api.github.com/user?access_token={0}", accessToken));
            }
            ApplicationUser user = JsonConvert.DeserializeObject <ApplicationUser>(userInformationString);

            user.CheckAndRepairUselessRequiredFields();
            ApplicationUser exisitingUser = await UserManager.FindByNameAsync(user.UserName);

            if (exisitingUser != null)
            {
                exisitingUser.AvatarUrl       = user.AvatarUrl;
                exisitingUser.Email           = user.Email;
                exisitingUser.GitHubId        = user.GitHubId;
                exisitingUser.HtmlUrl         = user.HtmlUrl;
                exisitingUser.RepositoriesUrl = user.RepositoriesUrl;
                exisitingUser.Url             = user.Url;
                IdentityResult idr = await UserManager.UpdateAsync(exisitingUser);
            }
            else
            {
                await UserManager.CreateAsync(user);

                exisitingUser = await UserManager.FindByNameAsync(user.UserName);
            }

            await AddExternalLogin(exisitingUser, accessToken);

            ClaimsIdentity oAuthIdentity = await exisitingUser.GenerateUserIdentityAsync(UserManager, DefaultAuthenticationTypes.ExternalBearer);

            AuthenticationProperties authProperties = ApplicationOAuthProvider.CreateProperties(exisitingUser.UserName);

            oAuthIdentity.AddClaims(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, accessToken),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                          "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

                new Claim(ClaimTypes.Name, exisitingUser.UserName),
                new Claim("Certificate", accessToken),
            });

            Authentication.SignIn(new AuthenticationProperties
            {
                IsPersistent = false,
            }, oAuthIdentity);


            return(Ok(new { Token = accessToken, user = exisitingUser }));
        }
Ejemplo n.º 14
0
        public async Task <object> Register()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            byte[] buffer = null;
            string filename;
            string email           = string.Empty;
            string username        = string.Empty;
            string password        = string.Empty;
            string confirmpassword = string.Empty;

            var fileManager = new AzureFileManager();

            foreach (var file in provider.Contents)
            {
                if (file.Headers.ContentDisposition.Name.Contains("email"))
                {
                    email = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("username"))
                {
                    username = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("password"))
                {
                    password = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("confirmpassword"))
                {
                    confirmpassword = await file.ReadAsStringAsync();
                }
                else
                {
                    filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    buffer   = await file.ReadAsByteArrayAsync();
                }
            }

            var model = new RegisterBindingModel()
            {
                email           = email,
                username        = username,
                password        = password,
                confirmpassword = confirmpassword,
            };

            logger.Log(LogLevel.Info, $"Register({model.email})");
            if (!ModelState.IsValid)
            {
                logger.Log(LogLevel.Error, $"Register({model.email}). Error: model state is not invalid");
                return(BadRequest(ModelState));
            }

            //var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
            var userInfo = UserManager2.CreateUserInfo("", username, "", "", "");

            var user = new User()
            {
                UserName      = model.email,
                PasswordHash  = model.password,
                IsActive      = true,
                UserInfoId    = userInfo.Id,
                UserType      = (int)UserTypeEnum.Client,
                AccountPlanId = (int)AccountPlanEnum.Start,
                Registration  = DateTime.Now,
                LastUpdate    = DateTime.Now
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            user = UserManager2.Create(user);
            //SignInManager.SignIn(user, false, false);
            ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);

            Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);

            var token = GetToken(model.email, model.password);

            //avatar
            var uploadResult = fileManager.UploadFileAsync(buffer, $"{user.Id}.png");//pass file stream

            if (string.IsNullOrEmpty(uploadResult.Result))
            {
                return(BadRequest(uploadResult.Result));
            }


            var info = UserManager2.FindUserInfo(user.UserInfoId);

            info.PhotoUrl = uploadResult.Result;
            UserManager2.UpdateInfo(info);
            try
            {
                GroupManager.CreateFavorites(user.Id);
            }
            catch (Exception ex)
            { }

            var usermodel = UserManager2.GetUserModel(user.UserName);

            return(new
            {
                token = token,
                user = usermodel
            });
        }
Ejemplo n.º 15
0
        public async Task <IHttpActionResult> RegisterWithExternalToken(LoginWithExternalTokenBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // validate token
            ExternalLoginData externalLogin = await FromToken(model.Provider, model.ExternalToken);

            if (externalLogin == null)
            {
                return(BadRequest("External login could not be found"));
            }

            if (externalLogin.LoginProvider != model.Provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                return(BadRequest("Login provider does not match"));
            }

            var passedLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);

            // if we reached this point then token is valid, so query the user
            var user = await UserManager.FindAsync(passedLoginInfo);

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                // the user has not been registered into the database yet
                // first we need to retrieve info for the user and register him/her

                user = await RetrieveUserDetailsWithProvider(model.Provider, model.ExternalToken);

                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    var userLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);

                    result = await UserManager.AddLoginAsync(user.Id, userLoginInfo);

                    if (result.Succeeded)
                    {
                        // TODO: gseng - add this user to the "asp_net_user_roles" table

                        AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                        Authentication.SignIn(properties);
                    }
                }
            }
            else
            {
                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties);
            }

            return(Ok());
        }
Ejemplo n.º 16
0
        public async Task <IHttpActionResult> LoginWithExternalToken(LoginWithExternalTokenBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // validate token
            ExternalLoginData externalLogin = await FromToken(model.Provider, model.ExternalToken);

            if (externalLogin == null)
            {
                return(BadRequest("External login could not be found"));
            }

            if (externalLogin.LoginProvider != model.Provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                return(BadRequest("Login provider does not match"));
            }

            var passedLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);

            // if we reached this point then token is valid, so query the user
            var user = await UserManager.FindAsync(passedLoginInfo);

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                return(BadRequest("User has not been registered yet, must be a business error."));
            }
            else
            {
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

                DateTime currentUtc = DateTime.UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));

                string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
                Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

                int expiryInDays = int.Parse(ConfigurationManager.AppSettings["TokenExpiryInDays"]);

                // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
                JObject token = new JObject(
                    new JProperty("userName", user.UserName),
                    new JProperty("access_token", accessToken),
                    new JProperty("token_type", "bearer"),
                    new JProperty("expires_in", TimeSpan.FromDays(expiryInDays).TotalSeconds.ToString()),
                    new JProperty("issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", CultureInfo.InvariantCulture)),
                    new JProperty("expires", currentUtc.Add(TimeSpan.FromDays(expiryInDays)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture))
                    );

                return(Ok(token));
            }
        }
Ejemplo n.º 17
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            string redirectUri = string.Empty;

            string redirectUriValidationResult = ValidateClientAndRedirectUri(Request, ref redirectUri);

            if (!string.IsNullOrWhiteSpace(redirectUriValidationResult))
            {
                return(BadRequest(redirectUriValidationResult));
            }

            if (error != null)
            {
                redirectUri = string.Format("{0}?&authenticated={1}&provider={2}&username={3}&token={4}&errorMessage={5}&operation={6}",
                                            redirectUri,
                                            "no",
                                            provider,
                                            "",
                                            "",
                                            Uri.EscapeDataString(error),
                                            "login");

                return(Redirect(redirectUri));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }


            ExternalLoginInfo info = await Authentication.GetExternalLoginInfoAsync();

            if (info == null)
            {
                redirectUri = string.Format("{0}?&authenticated={1}&provider={2}&username={3}&token={4}&errorMessage={5}&operation={6}",
                                            redirectUri,
                                            "no",
                                            provider,
                                            "",
                                            info.ExternalIdentity.ToString(),
                                            "The Provider refuses to Login!",
                                            "login");

                return(Redirect(redirectUri));
            }

            // get the claims identity
            ClaimsIdentity claimsIdentity = GetBasicUserIdentity(info);

            // search for a user with this Login authorized
            CustomUser user = await userManager.FindAsync(info.Login);

            if (user == null)
            {
                redirectUri = string.Format("{0}?&authenticated={1}&provider={2}&username={3}&token={4}&errorMessage={5}&operation={6}",
                                            redirectUri,
                                            "no",
                                            provider,
                                            info.DefaultUserName,
                                            info.ExternalIdentity.ToString(),
                                            "There are no User with the login " + info.DefaultUserName + " associated!",
                                            "login");

                return(Redirect(redirectUri));
            }

            ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            var hash = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            redirectUri = string.Format("{0}?&authenticated={1}&provider={2}&username={3}&token={4}&errorMessage={5}&operation={6}",
                                        redirectUri,
                                        "yes",
                                        provider,
                                        user.UserName,
                                        hash,
                                        "",
                                        "login");

            return(Redirect(redirectUri));
        }
Ejemplo n.º 18
0
        public async Task <IHttpActionResult> RegisterExternal()
        {
            var info = await Authentication.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(InternalServerError());
            }
            string firstName;
            string lastName;
            string gender;

            if (info.Login.LoginProvider == "Google")
            {
                var externalIdentity = Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                lastName  = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname).Value;
                firstName = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName).Value;
                //         birthday = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.DateOfBirth).Value;
                gender = "male";
            }
            else
            {
                var accessToken = Authentication.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie).FindFirstValue("FacebookAccessToken");
                var fb          = new FacebookClient(accessToken);
                //    dynamic aaa = fb.Get("/me");
                dynamic myInfo = fb.Get("/me?fields=id,email,first_name,last_name,gender");
                lastName  = myInfo["last_name"];
                firstName = myInfo["first_name"];
                gender    = myInfo["gender"];
            }
            Gender _gender = Gender.MALE;

            if (gender.Equals("female"))
            {
                _gender = Gender.FEMALE;
            }



            var userExtend = new Model.Model.UserExtend();

            var user = new ApplicationUser()
            {
                UserName       = info.Email,
                Email          = info.Email,
                FirstName      = firstName,
                LastName       = lastName,
                User           = userExtend,
                EmailConfirmed = true,
                Birthday       = null,
                Gender         = _gender
            };

            try
            {
                IdentityResult result = await UserManager.CreateAsync(user);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }


                result = await UserManager.AddLoginAsync(user.Id, info.Login);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }

                result = await UserManager.AddToRoleAsync(user.Id, "User");

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                var role   = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).FirstOrDefault().Value;
                var userId = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName, role, userId);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
                return(Ok(properties.Dictionary));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Ejemplo n.º 19
0
        public async Task <IHttpActionResult> LoginUsingExternalProvider(ProviderAndAccessToken model)
        {
            string           id          = null;
            string           userName    = null;
            string           accessToken = null;
            ExternalProvider externalProvider;

            if (!Enum.TryParse <ExternalProvider>(model.Provider, out externalProvider))
            {
                return(BadRequest($"Invalid provider : {model.Provider}"));
            }

            if (externalProvider == ExternalProvider.facebook)
            {
                try
                {
                    var     fbclient = new Facebook.FacebookClient(model.Token);
                    dynamic fb       = fbclient.Get("/me?locale=en_US&fields=name,email");
                    id       = fb.id;
                    userName = fb.email;
                }
                catch (Exception ex)
                {
                    HttpContent contentPost = new StringContent("Facebook : " + ex.Message, Encoding.UTF8, "application/text");
                    var         msg         = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        Content = contentPost
                    };
                    throw new HttpResponseException(msg);
                }
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(model.Provider, id));

            var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddDays(Settings.TokenExpirationDurationInDays)
            };
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                 CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);

            Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            identity.AddClaim(new Claim("role", "user"));
            var ticket = new AuthenticationTicket(identity, props);

            accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            return(Ok(new { access_token = accessToken }));
        }