コード例 #1
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);

        }
コード例 #2
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) {

            // 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);

        }
コード例 #3
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);

        }
コード例 #4
0
 private MicrosoftService(MicrosoftOAuthClient client) {
     Client = client;
     WindowsLive = new WindowsLiveEndpoint(this);
 }
コード例 #5
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.MicrosoftAppId) ||
                string.IsNullOrEmpty(SiteConstants.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.MicrosoftAppId,
                    ClientSecret = SiteConstants.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 = string.Format("Unable to acquire access token<br/>{0}", 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 = user.Emails != null && !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 = string.Format("https://apis.live.net/v5.0/{0}/picture", user.Id)
                                };

                                //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 = string.Format("Unable to get user information<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }



            }


            ShowMessage(resultMessage);
            return RedirectToAction("LogOn", "Members");
        }
コード例 #6
0
 internal WindowsLiveRawEndpoint(MicrosoftOAuthClient client) {
     Client = client;
 }