Exemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance based on the specified refresh token.
        /// </summary>
        /// <param name="clientId">The client ID.</param>
        /// <param name="clientSecret">The client secret.</param>
        /// <param name="refreshToken">The refresh token of the user.</param>
        public static MicrosoftService CreateFromRefreshToken(string clientId, string clientSecret, string refreshToken)
        {
            // Some validation
            if (String.IsNullOrWhiteSpace(clientId))
            {
                throw new ArgumentNullException("clientId");
            }
            if (String.IsNullOrWhiteSpace(clientSecret))
            {
                throw new ArgumentNullException("clientSecret");
            }
            if (String.IsNullOrWhiteSpace(refreshToken))
            {
                throw new ArgumentNullException("refreshToken");
            }

            // Initialize a new OAuth client
            MicrosoftOAuthClient client = new MicrosoftOAuthClient(clientId, clientSecret);

            // Get an access token from the refresh token.
            MicrosoftTokenResponse response = client.GetAccessTokenFromRefreshToken(refreshToken);

            // Update the OAuth client with the access token
            client.AccessToken = response.Body.AccessToken;

            // Initialize a new service instance
            return(new MicrosoftService(client));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initialize a new service instance from the specified OAuth client.
        /// </summary>
        /// <param name="client">The OAuth client.</param>
        public static MicrosoftService CreateFromOAuthClient(MicrosoftOAuthClient client)
        {
            // This should never be null
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            // Initialize the service
            return(new MicrosoftService(client));
        }
 internal WindowsLiveRawEndpoint(MicrosoftOAuthClient client)
 {
     Client = client;
 }
Exemplo n.º 4
0
        public ActionResult MicrosoftLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            var input = new
            {
                Code  = AuthCode,
                State = AuthState,
                Error = new
                {
                    HasError         = !String.IsNullOrWhiteSpace(AuthError),
                    Text             = AuthError,
                    ErrorDescription = AuthErrorDescription
                }
            };


            // Get the prevalue options
            if (string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppId) ||
                string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppSecret))
            {
                resultMessage.Message     = "You need to add the Microsoft app credentials to the web.config";
                resultMessage.MessageType = GenericMessages.danger;
            }
            else
            {
                var client = new MicrosoftOAuthClient
                {
                    ClientId     = SiteConstants.Instance.MicrosoftAppId,
                    ClientSecret = SiteConstants.Instance.MicrosoftAppSecret,
                    RedirectUri  = ReturnUrl
                };

                // Session expired?
                if (input.State != null && Session["MVCForum_" + input.State] == null)
                {
                    resultMessage.Message     = "Session Expired";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Check whether an error response was received from Microsoft
                if (input.Error.HasError)
                {
                    Session.Remove("MVCForum_" + input.State);
                    resultMessage.Message     = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Redirect the user to the Microsoft login dialog
                if (string.IsNullOrWhiteSpace(input.Code))
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["MVCForum_" + state] = "/";

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, WindowsLiveScopes.Emails + WindowsLiveScopes.Birthday);

                    // Redirect the user
                    return(Redirect(url));
                }

                // Exchange the authorization code for an access token
                MicrosoftTokenResponse accessTokenResponse;
                try
                {
                    Session.Remove("MVCForum_" + input.State);
                    accessTokenResponse = client.GetAccessTokenFromAuthCode(input.Code);
                }
                catch (Exception ex)
                {
                    accessTokenResponse       = null;
                    resultMessage.Message     = $"Unable to acquire access token<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                }


                try
                {
                    if (string.IsNullOrEmpty(resultMessage.Message) || accessTokenResponse != null)
                    {
                        //MicrosoftScope debug = accessTokenResponse.Body.Scope.Items;

                        //accessTokenResponse.Body.AccessToken
                        //foreach (MicrosoftScope scope in accessTokenResponse.Body.Scope.Items) {
                        //    scope
                        //}
                        //accessTokenResponse.Response.Body

                        // Initialize a new MicrosoftService so we can make calls to the API
                        var service = MicrosoftService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken);

                        // Make the call to the Windows Live API / endpoint
                        var response = service.WindowsLive.GetSelf();

                        // Get a reference to the response body
                        var user = response.Body;

                        var getEmail = !string.IsNullOrWhiteSpace(user.Emails?.Preferred);
                        if (!getEmail)
                        {
                            resultMessage.Message     = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress");
                            resultMessage.MessageType = GenericMessages.danger;
                            ShowMessage(resultMessage);
                            return(RedirectToAction("LogOn", "Members"));
                        }

                        using (UnitOfWorkManager.NewUnitOfWork())
                        {
                            var userExists = MembershipService.GetUserByEmail(user.Emails.Preferred);

                            if (userExists != null)
                            {
                                try
                                {
                                    // Users already exists, so log them in
                                    FormsAuthentication.SetAuthCookie(userExists.UserName, true);
                                    resultMessage.Message     = LocalizationService.GetResourceString("Members.NowLoggedIn");
                                    resultMessage.MessageType = GenericMessages.success;
                                    ShowMessage(resultMessage);
                                    return(RedirectToAction("Index", "Home"));
                                }
                                catch (Exception ex)
                                {
                                    LoggingService.Error(ex);
                                }
                            }
                            else
                            {
                                // Not registered already so register them
                                var viewModel = new MemberAddViewModel
                                {
                                    Email                 = user.Emails.Preferred,
                                    LoginType             = LoginType.Microsoft,
                                    Password              = StringUtils.RandomString(8),
                                    UserName              = user.Name,
                                    UserAccessToken       = accessTokenResponse.Body.AccessToken,
                                    SocialProfileImageUrl = $"https://apis.live.net/v5.0/{user.Id}/picture"
                                };

                                //var uri = string.Concat("https://apis.live.net/v5.0/me?access_token=",viewModel.UserAccessToken);
                                //using (var dl = new WebClient())
                                //{
                                //    var profile = JObject.Parse(dl.DownloadString(uri));
                                //    var pictureUrl = ;
                                //    if (!string.IsNullOrEmpty(pictureUrl))
                                //    {
                                //        //viewModel.SocialProfileImageUrl = getImageUrl;
                                //    }
                                //}


                                // Store the viewModel in TempData - Which we'll use in the register logic
                                TempData[AppConstants.MemberRegisterViewModel] = viewModel;

                                return(RedirectToAction("SocialLoginValidator", "Members"));
                            }
                        }
                    }
                    else
                    {
                        resultMessage.MessageType = GenericMessages.danger;
                        ShowMessage(resultMessage);
                        return(RedirectToAction("LogOn", "Members"));
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = $"Unable to get user information<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }
            }


            ShowMessage(resultMessage);
            return(RedirectToAction("LogOn", "Members"));
        }
        public ActionResult MicrosoftLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            var input = new
            {
                Code  = AuthCode,
                State = AuthState,
                Error = new
                {
                    HasError         = !string.IsNullOrWhiteSpace(AuthError),
                    Text             = AuthError,
                    ErrorDescription = AuthErrorDescription
                }
            };


            // Get the prevalue options
            if (string.IsNullOrEmpty(Dialogue.Settings().MicrosoftAppId) ||
                string.IsNullOrEmpty(Dialogue.Settings().MicrosoftAppSecret))
            {
                resultMessage.Message     = "You need to add the Microsoft app credentials to the web.config";
                resultMessage.MessageType = GenericMessages.Danger;
            }
            else
            {
                var client = new MicrosoftOAuthClient
                {
                    ClientId     = Dialogue.Settings().MicrosoftAppId,
                    ClientSecret = Dialogue.Settings().MicrosoftAppSecret,
                    RedirectUri  = ReturnUrl
                };

                // Session expired?
                if (input.State != null && Session["Dialogue_" + input.State] == null)
                {
                    resultMessage.Message     = "Session Expired";
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                // Check whether an error response was received from Microsoft
                if (input.Error.HasError)
                {
                    Session.Remove("Dialogue_" + input.State);
                    resultMessage.Message     = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                // Redirect the user to the Microsoft login dialog
                if (string.IsNullOrWhiteSpace(input.Code))
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["Dialogue_" + state] = "/";

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, WindowsLiveScopes.Emails + WindowsLiveScopes.Birthday);

                    // Redirect the user
                    return(Redirect(url));
                }

                // Exchange the authorization code for an access token
                MicrosoftTokenResponse accessTokenResponse;
                try
                {
                    Session.Remove("Dialogue_" + input.State);
                    accessTokenResponse = client.GetAccessTokenFromAuthCode(input.Code);
                }
                catch (Exception ex)
                {
                    accessTokenResponse       = null;
                    resultMessage.Message     = $"Unable to acquire access token<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.Danger;
                }


                try
                {
                    if (string.IsNullOrEmpty(resultMessage.Message) || accessTokenResponse != null)
                    {
                        //MicrosoftScope debug = accessTokenResponse.Body.Scope.Items;

                        // Initialize a new MicrosoftService so we can make calls to the API
                        var service = MicrosoftService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken);

                        // Make the call to the Windows Live API / endpoint
                        var response = service.WindowsLive.GetSelf();

                        // Get a reference to the response body
                        var user = response.Body;

                        var getEmail = !string.IsNullOrWhiteSpace(user.Emails?.Preferred);
                        if (!getEmail)
                        {
                            resultMessage.Message     = "Unable to get email address from Microsoft account";
                            resultMessage.MessageType = GenericMessages.Danger;
                            ShowMessage(resultMessage);
                            return(RedirectToUmbracoPage(Dialogue.Settings().ForumId));
                        }

                        using (UnitOfWorkManager.NewUnitOfWork())
                        {
                            var userExists = AppHelpers.UmbServices().MemberService.GetByEmail(user.Emails.Preferred);

                            if (userExists != null)
                            {
                                try
                                {
                                    // Update access token
                                    userExists.Properties[AppConstants.PropMemberMicrosoftAccessToken].Value = accessTokenResponse.Body.AccessToken;
                                    AppHelpers.UmbServices().MemberService.Save(userExists);

                                    // Users already exists, so log them in
                                    FormsAuthentication.SetAuthCookie(userExists.Username, true);
                                    resultMessage.Message     = Lang("Members.NowLoggedIn");
                                    resultMessage.MessageType = GenericMessages.Success;
                                }
                                catch (Exception ex)
                                {
                                    AppHelpers.LogError(ex);
                                }
                            }
                            else
                            {
                                // Not registered already so register them
                                var viewModel = new RegisterViewModel
                                {
                                    Email                 = user.Emails.Preferred,
                                    LoginType             = LoginType.Microsoft,
                                    Password              = AppHelpers.RandomString(8),
                                    UserName              = user.Name,
                                    SocialProfileImageUrl = $"https://apis.live.net/v5.0/{user.Id}/picture",
                                    UserAccessToken       = accessTokenResponse.Body.AccessToken
                                };

                                return(RedirectToAction("MemberRegisterLogic", "DialogueRegister", viewModel));
                            }
                        }
                    }
                    else
                    {
                        resultMessage.MessageType = GenericMessages.Danger;
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = $"Unable to get user information<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.Danger;
                }
            }


            ShowMessage(resultMessage);
            return(RedirectToUmbracoPage(Dialogue.Settings().ForumId));
        }
Exemplo n.º 6
0
 private MicrosoftService(MicrosoftOAuthClient client)
 {
     Client      = client;
     WindowsLive = new WindowsLiveEndpoint(this);
 }