Exemplo n.º 1
0
        private dynamic AuthorizeByExternalProvider(ProviderAndAccessToken model, ExternalProvider externalProvider)
        {
            IKernel        kernel        = Infrastructure.DependencyResolver.GetKernel();
            IOauthProvider oauthProvider = kernel.Get <IOauthProvider>(externalProvider.ToString());

            try
            {
                dynamic userData = oauthProvider.Authorize(model);
                userData.userName = userData.userData.userName.Replace(" ", "");
                if (!userData.userName.ToString().Contains("@")) //google already adds @gmail.com to returned data so this should be optional.
                {
                    userData.userName = userData.userName + "@" + externalProvider.ToString() + ".com";
                }
                return(userData);
            }
            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);
            }
        }
Exemplo n.º 2
0
        public async Task <IHttpActionResult> LoginUsingExternalProvider(ProviderAndAccessToken model)
        {
            ExternalProvider externalProvider;

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

            dynamic userData = AuthorizeByExternalProvider(model, externalProvider);

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

            return(Ok(new { access_token = getServiceAccessToken(user) }));
        }
Exemplo n.º 3
0
        public async Task <IHttpActionResult> RegisterUsingExternalProvider(ProviderAndAccessToken model)
        {
            ExternalProvider externalProvider;

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

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

            if (user != null || (await UserManager.FindByEmailAsync(userData.userName) != null || await UserManager.FindByNameAsync(userData.userName) != null))
            {
                return(BadRequest($"{userData.userName} is already registered"));
            }

            user = new ServiceUser()
            {
                UserName = userData.userName, Email = userData.userName
            };

            IdentityResult result = await UserManager.CreateAsync(user);

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

            result = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(model.Provider, userData.id));

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

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

            return(Ok(new { access_token = getServiceAccessToken(user) }));
        }
Exemplo n.º 4
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 }));
        }
Exemplo n.º 5
0
        public async Task <IHttpActionResult> RegisterUsingExternalProvider(ProviderAndAccessToken model)
        {
            string           id       = null;
            string           userName = 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;
                    if (userName == null)
                    {
                        userName = fb.name;
                    }
                    if (userName == null)
                    {
                        userName = fb.id;
                    }
                    userName = userName.Replace(" ", "") + "@facebook.com";
                }
                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);
                }
            }

            //TODO: Google, LinkedIn

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

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                if (await UserManager.FindByEmailAsync(userName) != null || await UserManager.FindByNameAsync(userName) != null)
                {
                    return(BadRequest($"{userName} is already registered"));
                }

                user = new ApplicationUser()
                {
                    UserName = userName, Email = userName
                };

                IdentityResult result = await UserManager.CreateAsync(user);

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

                result = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(model.Provider, id));

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

            return(Ok("Registered successfully"));
        }