Esempio n. 1
0
        public async Task GetAuthorizationRequestUrlTest()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant);
            Uri uri     = null;

            try
            {
                uri = await context.GetAuthorizationRequestUrlAsync(null, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId), "extra=123");
            }
            catch (ArgumentNullException ex)
            {
                Assert.AreEqual(ex.ParamName, "resource");
            }

            uri = await context.GetAuthorizationRequestUrlAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId), "extra=123");

            Assert.IsNotNull(uri);
            Assert.IsTrue(uri.AbsoluteUri.Contains("login_hint"));
            Assert.IsTrue(uri.AbsoluteUri.Contains("extra=123"));
            uri = await context.GetAuthorizationRequestUrlAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, UserIdentifier.AnyUser, null);

            Assert.IsNotNull(uri);
            Assert.IsFalse(uri.AbsoluteUri.Contains("login_hint"));
            Assert.IsFalse(uri.AbsoluteUri.Contains("client-request-id="));
            context.CorrelationId = Guid.NewGuid();
            uri = await context.GetAuthorizationRequestUrlAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId), "extra");

            Assert.IsNotNull(uri);
            Assert.IsTrue(uri.AbsoluteUri.Contains("client-request-id="));
        }
Esempio n. 2
0
        public static async Task <DataStore> GetUserTokenFromPopup()
        {
#if DEBUG
            AuthenticationContext context = new AuthenticationContext("https://login.windows.net/" + Credential.Instance.AAD.TenantId);
            var url = context.GetAuthorizationRequestUrlAsync(Constants.AzureManagementCoreApi, Constants.MicrosoftClientId, new Uri("https://unittest/redirect.html"), UserIdentifier.AnyUser, "").Result;
            WindowsFormsWebAuthenticationDialog form = new WindowsFormsWebAuthenticationDialog(null);
            form.WebBrowser.Navigated += delegate(object sender, WebBrowserNavigatedEventArgs args)
            {
                if (args.Url.ToString().StartsWith("https://unittest/redirect.html"))
                {
                    string tempcode = args.Url.ToString();
                    tempcode = tempcode.Substring(tempcode.IndexOf("code=") + 5);
                    code     = tempcode.Substring(0, tempcode.IndexOf("&"));
                    form.Close();
                }
                ;
            };
            form.WebBrowser.Navigate(url);
            form.ShowBrowser();

            while (string.IsNullOrEmpty(code))
            {
                await Task.Delay(5000);
            }
#endif

            DataStore datastore = new DataStore();
            datastore.AddToDataStore("code", code, DataStoreType.Private);
            datastore.AddToDataStore("AADTenant", "common", DataStoreType.Private);
            datastore.AddToDataStore("AADRedirect", "https://unittest/redirect.html");
            var result = await TestManager.ExecuteActionAsync("Microsoft-GetAzureToken", datastore);

            return(result.DataStore);
        }
        protected void SetupControl()
        {
            if (StopProcessing)
            {
                return;
            }

            try
            {
                var returnUrl = string.IsNullOrWhiteSpace(Settings.AzureADAuthenticationSettings.RedirectAfterLoginPageUrl)
                    ? HttpContext.Current.Request.RawUrl
                    : Settings.AzureADAuthenticationSettings.RedirectAfterLoginPageUrl;

                var authContext =
                    new AuthenticationContext(string.Format(Settings.AzureADAuthenticationSettings.AuthorityUrl,
                                                            Settings.AzureADAuthenticationSettings.TenantId));
                var authorizationUrl = authContext.GetAuthorizationRequestUrlAsync(
                    string.Format(Settings.AzureADAuthenticationSettings.GraphUrl, ""),
                    Settings.AzureADAuthenticationSettings.ClientId,
                    new Uri(URLHelper.GetAbsoluteUrl(Settings.AzureADAuthenticationSettings
                                                     .AuthenticationRedirectPage)), UserIdentifier.AnyUser, $"state={returnUrl}")
                                       .GetAwaiter()
                                       .GetResult();
                btnAzureSignIn.NavigateUrl = authorizationUrl.AbsoluteUri.Replace("form_post", "query");
            }
            catch (Exception exception)
            {
                EventLogProvider.LogException("AzureActiveDirectory", "Login", exception);
                Visible = false;
            }

            DataBind();
        }
        protected async void SetupControl()
        {
            if (StopProcessing)
            {
                return;
            }
            var authContext =
                new AuthenticationContext(string.Format(Constants.AzureActiveDirectory.Authority,
                                                        Constants.AzureActiveDirectory.TenantId));
            var authorizationUrl =
                await
                authContext.GetAuthorizationRequestUrlAsync(
                    string.Format(Constants.AzureActiveDirectory.GraphResourceUri, ""),
                    Constants.AzureActiveDirectory.ClientId,
                    new Uri(URLHelper.GetAbsoluteUrl(Constants.AzureActiveDirectory.KenticoRedirectPage)),
                    UserIdentifier.AnyUser, null);

            btnAzureSignIn.NavigateUrl = authorizationUrl.AbsoluteUri;
            var returnUrl = HttpContext.Current.Request.GetReturnUrl(null);

            if (returnUrl.IsNotEmpty())
            {
                SessionHelper.SetValue("returnurl", returnUrl);
            }
            DataBind();
        }
        public async Task <string> GetAuthorizationRequestUrlAsync(string authority, string resource, string clientId, Uri redirectUri, string extraQueryParameters)
        {
            AuthenticationContext authContext;
            Uri authUri;

            authority.AssertNotEmpty(nameof(authority));
            resource.AssertNotEmpty(nameof(resource));
            redirectUri.AssertNotNull(nameof(redirectUri));

            try
            {
                authContext = new AuthenticationContext(authority);

                authUri = await authContext.GetAuthorizationRequestUrlAsync(
                    resource,
                    clientId,
                    redirectUri,
                    UserIdentifier.AnyUser,
                    extraQueryParameters).ConfigureAwait(false);

                return(authUri.ToString());
            }
            finally
            {
                authContext = null;
            }
        }
Esempio n. 6
0
        public async Task <ActionResult> GetRefreshTokenUrl()
        {
            AuthenticationContext authContext = new AuthenticationContext(SettingCollectionFactoryInternal.DemoWebSettingCollection[DemoWebSettingEnum.Authority].ToString(), false);
            Uri redirectUri      = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth/Login");
            Uri authorizationUrl = await authContext.GetAuthorizationRequestUrlAsync(
                SettingCollectionFactoryInternal.DemoWebSettingCollection[DemoWebSettingEnum.GraphResourceId].ToString(),
                SettingCollectionFactoryInternal.DemoWebSettingCollection[DemoWebSettingEnum.ClientId].ToString(), redirectUri, UserIdentifier.AnyUser, null);

            return(this.Content(authorizationUrl.AbsoluteUri));
        }
        /// <summary>
        /// 導向 OAuth 登入頁面
        /// </summary>
        /// <returns></returns>
        public ActionResult RedirectToSignInPage()
        {
            AuthenticationContext authContext = new AuthenticationContext(SettingCollectionFactoryInternal.DemoWebSettingCollection[DemoWebSettingEnum.Authority].ToString(), false);
            Uri redirectUri      = new Uri(base.Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth/Login");
            Uri authorizationUrl = authContext.GetAuthorizationRequestUrlAsync(
                SettingCollectionFactoryInternal.DemoWebSettingCollection[DemoWebSettingEnum.GraphResourceId].ToString(),
                SettingCollectionFactoryInternal.DemoWebSettingCollection[DemoWebSettingEnum.ClientId].ToString(), redirectUri, UserIdentifier.AnyUser, null).Result;

            return(base.Redirect(authorizationUrl.AbsoluteUri));
        }
Esempio n. 8
0
        /// <summary>
        ///     Get a url string to sign in Microsoft account.
        /// </summary>
        /// <param name="onSuccessRedirectUri"></param>
        /// <param name="additionalScopes"></param>
        /// <returns></returns>
        public async Task <string> GetMicrosoftSignInUrl(Uri onSuccessRedirectUri, string[] additionalScopes = null)
        {
            var authContext = new AuthenticationContext(_authorityUrl);

            // Generate the parameterized URL for Azure signin
            var authUri = await authContext.GetAuthorizationRequestUrlAsync(Scopes, additionalScopes, _clientId,
                                                                            onSuccessRedirectUri, UserIdentifier.AnyUser, null);

            // Redirect the browser to the Azure signin page
            return(authUri.ToString());
        }
        public async Task <string> GetAuthUrlAsync(AuthenticationOptions authOptions, string state)
        {
            Uri redirectUri = new Uri(authOptions.RedirectUrl);
            AuthenticationContext context = new AuthenticationContext(authOptions.Authority);
            var uri = await context.GetAuthorizationRequestUrlAsync(
                authOptions.ResourceId,
                authOptions.ClientId,
                redirectUri,
                Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser,
                $"state={state}");

            return(uri.ToString());
        }
Esempio n. 10
0
        // GET: Auth
        public ActionResult Login()
        {
            AuthenticationContext authContext = new AuthenticationContext(Settings.microsoftLoginUrl);
            var authUri = authContext.GetAuthorizationRequestUrlAsync(
                Settings.graphApiEndpoint,
                ConfigurationManager.AppSettings["ClientId"],
                new Uri($"{ConfigurationManager.AppSettings["AppUrl"]}/Auth/Authorize"),
                UserIdentifier.AnyUser,
                null
                );

            return(Redirect(authUri.Result.ToString()));
        }
        public async Task <ActionResult> SignIn()
        {
            var authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority);

            // The url in our app that Azure should redirect to after successful signin
            Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

            // Generate the parameterized URL for Azure signin
            Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(SettingsHelper.MicrosoftGraphResource, SettingsHelper.ClientId, redirectUri, UserIdentifier.AnyUser, null);

            // Redirect the browser to the Azure signin page
            return(Redirect(authUri.ToString()));
        }
Esempio n. 12
0
        public async Task<IActionResult> SignIn()
        {
            string authority = "https://login.microsoftonline.com/common";
            AuthenticationContext authContext = new AuthenticationContext(authority);

            Uri redirectUri = new Uri(Url.Action("Authorize", "Outlook", null, "http"));

            // Generate the parameterized URL for Azure signin
            Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, ClientId,
                redirectUri, UserIdentifier.AnyUser, null);

            // Redirect the browser to the Azure signin page
            return Redirect(authUri.ToString());
        }
Esempio n. 13
0
        public async Task<ActionResult> SignIn()
        {
            string authority = "https://login.microsoftonline.com/common";
            string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"]; 
            AuthenticationContext authContext = new AuthenticationContext(authority);

            // The url in our app that Azure should redirect to after successful signin
            Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

            // Generate the parameterized URL for Azure signin
            Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, clientId, redirectUri, UserIdentifier.AnyUser, null);

            // Redirect the browser to the Azure signin page
            return Redirect(authUri.ToString());
        }
Esempio n. 14
0
        public ActionResult Login(string userid)
        {
            ///// Here I'm using im-memory session,
            ///// but please use other session store for scaling.
            Session["skypeuserid"] = userid;

            var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
            var authUri     = authContext.GetAuthorizationRequestUrlAsync(
                "https://outlook.office365.com/",
                ConfigurationManager.AppSettings["ClientId"],
                new Uri($"{ConfigurationManager.AppSettings["AppWebSite"]}/Home/Authorize"),
                UserIdentifier.AnyUser,
                null);

            return(Redirect(authUri.Result.ToString()));

            //return Redirect("https://localhost/test");
        }
Esempio n. 15
0
        public ActionResult Login(string channelId, string userId, string userName, string fromId, string fromName, string serviceUrl, string conversationId, string extraQueryParams)
        {
            // CRM Url
            Session["fromId"]         = fromId;
            Session["fromName"]       = fromName;
            Session["serviceUrl"]     = serviceUrl;
            Session["conversationId"] = conversationId;
            Session["channelId"]      = channelId;
            Session["userId"]         = userId;
            Session["userName"]       = userName;
            ChatState state = ChatState.RetrieveChatState(Session["channelId"].ToString(), Session["userId"].ToString());

            AuthenticationContext authContext = new AuthenticationContext(ConfigurationManager.AppSettings["CrmAuthority"]);
            var authUri = authContext.GetAuthorizationRequestUrlAsync(state.OrganizationUrl, ConfigurationManager.AppSettings["CrmClientId"],
                                                                      new Uri(ConfigurationManager.AppSettings["CrmRedirectUrl"]), UserIdentifier.AnyUser, extraQueryParams);

            return(Redirect(authUri.Result.ToString()));
        }
Esempio n. 16
0
        public async Task <ActionResult> Login()
        {
            if (string.IsNullOrEmpty(Const.Settings.ClientId) || string.IsNullOrEmpty(Const.Settings.ClientSecret))
            {
                ViewBag.Message = "Please set your client ID and client secret in the Web.config file";
                return(View());
            }

            var authContext = new AuthenticationContext(Const.Settings.AzureADAuthority);

            // Generate the parameterized URL for Azure login.
            Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(
                Const.Settings.GraphApiResource,
                Const.Settings.ClientId,
                loginRedirectUri,
                UserIdentifier.AnyUser,
                null);

            // Redirect the browser to the login page, then come back to the Authorize method below.
            return(Redirect(authUri.ToString()));
        }
Esempio n. 17
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = clientId,
                Authority             = authority,
                RedirectUri           = postLogoutRedirectUri,
                PostLogoutRedirectUri = postLogoutRedirectUri
                ,
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code                          = context.Code;
                        var redirectUrl                   = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        var consentRedirectUrl            = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/Admin/Result");
                        ClientCredential credential       = new ClientCredential(clientId, appKey);
                        AuthenticationContext authContext = new AuthenticationContext(authority);

                        string userObjectID             = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                        UserIdentifier userIdentifier   = new UserIdentifier(userObjectID, UserIdentifierType.UniqueId);
                        AuthenticationHelper.consentUrl = authContext.GetAuthorizationRequestUrlAsync(sharePointUrl, clientId, consentRedirectUrl, userIdentifier, "prompt=admin_consent").Result.ToString();

                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(code, redirectUrl, credential, resourceId).Result;
                        AuthenticationHelper.token  = result.AccessToken;

                        AuthenticationResult spResult        = authContext.AcquireTokenByAuthorizationCodeAsync(code, redirectUrl, credential, sharePointUrl).Result;
                        AuthenticationHelper.sharePointToken = spResult.AccessToken;

                        return(Task.FromResult(0));
                    }
                }
            });
        }
    public async Task<ActionResult> Index()
    {

      // By using this version of the AuthenticationContext constructor,
      // we are using the default in-memory token cache. In a real app, you would
      // want to provide an implementation of TokenCache that saves the data somewhere
      // so that you could persist it if restarting the app, etc.
      AuthenticationContext authContext = new AuthenticationContext(authority);

      ClientCredential credential = new ClientCredential(appId, appSecret);
      AuthenticationResult authResult = null;

      ViewBag.Message = TempData["message"];

      try
      {
        authResult = await authContext.AcquireTokenSilentAsync(scopes, credential, UserIdentifier.AnyUser);

        ViewBag.UserName = GetUserEmail(authContext, appId);
      }
      catch (AdalException ex)
      {
        if (ex.ErrorCode == "failed_to_acquire_token_silently")
        {
          // We don't have a token in the cache OR the token couldn't be refreshed
          // We need to have the user sign in
          Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
          ViewBag.LoginUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, appId, redirectUri, UserIdentifier.AnyUser, null);
        }
        else
        {
          TempData["error_message"] = ex.Message;
          RedirectToAction("Error");
        }
      }

      return View();
    }
        //
        // GET: /UserProfile/
        public async Task <ActionResult> Index(string authError)
        {
            UserProfile           profile     = null;
            AuthenticationContext authContext = null;
            AuthenticationResult  result      = null;
            bool           reauth             = false;
            string         userObjectID       = string.Empty;
            UserIdentifier user = UserIdentifier.AnyUser;

            var claimsIdentity = (ClaimsIdentity)ClaimsPrincipal.Current?.Identity;

            if (claimsIdentity != null && claimsIdentity.IsAuthenticated)
            {
                //userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
                userObjectID = claimsIdentity.Claims.FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
                user         = new UserIdentifier(claimsIdentity.Name, UserIdentifierType.OptionalDisplayableId);
            }

            try
            {
                ClientCredential credential = new ClientCredential(Startup.clientId, Startup.clientSecret);
                authContext = new AuthenticationContext(Startup.Authority, new TokenDbCache(userObjectID));

                if (authError != null)
                {
                    Uri    redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");
                    string state       = GenerateState(userObjectID, Request.Url.ToString());
                    ViewBag.AuthorizationUrl = await authContext.GetAuthorizationRequestUrlAsync(Startup.graphResourceId, Startup.clientId, redirectUri, user, state == null?null : "&state=" + state);

                    profile              = new UserProfile();
                    profile.DisplayName  = " ";
                    profile.GivenName    = " ";
                    profile.Surname      = " ";
                    ViewBag.ErrorMessage = "UnexpectedError";
                    return(View(profile));
                }

                result = await authContext.AcquireTokenSilentAsync(Startup.graphResourceId, credential, UserIdentifier.AnyUser);
            }
            catch (AdalException e)
            {
                if (e.ErrorCode == "failed_to_acquire_token_silently")
                {
                    // Capture error for handling outside of catch block
                    reauth = true;
                }
                else
                {
                    ViewBag.ErrorMessage = "Error while Acquiring Token from Cache.";
                    return(View("Error"));
                }
            }

            if (reauth)
            {
                // The user needs to re-authorize.  Show them a message to that effect.
                // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.

                profile              = new UserProfile();
                profile.DisplayName  = " ";
                profile.GivenName    = " ";
                profile.Surname      = " ";
                ViewBag.ErrorMessage = "AuthorizationRequired";

                authContext = new AuthenticationContext(Startup.Authority);
                Uri redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");

                string state = this.GenerateState(userObjectID, Request.Url.ToString());

                ViewBag.AuthorizationUrl = await authContext.GetAuthorizationRequestUrlAsync(Startup.graphResourceId, Startup.clientId, redirectUri, user, state == null?null : "&state=" + state);

                return(View(profile));
            }


            try
            {
                //
                // Call the Graph API and retrieve the user's profile.
                //
                string requestUrl = String.Format(
                    CultureInfo.InvariantCulture,
                    Startup.graphUserUrl,
                    HttpUtility.UrlEncode(result.TenantId));
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                //
                // Return the user's profile in the view.
                //
                if (response.IsSuccessStatusCode)
                {
                    string responseString = await response.Content.ReadAsStringAsync();

                    profile = JsonConvert.DeserializeObject <UserProfile>(responseString);
                    return(View(profile));
                }
                else if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    //
                    // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again.
                    //
                    authContext.TokenCache.Clear();

                    Uri    redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");
                    string state       = GenerateState(userObjectID, Request.Url.ToString());
                    ViewBag.AuthorizationUrl = await authContext.GetAuthorizationRequestUrlAsync(Startup.graphResourceId, Startup.clientId, redirectUri, UserIdentifier.AnyUser, state == null?null : "&state=" + state);

                    profile              = new UserProfile();
                    profile.DisplayName  = " ";
                    profile.GivenName    = " ";
                    profile.Surname      = " ";
                    ViewBag.ErrorMessage = "UnexpectedError";
                    return(View(profile));
                }

                ViewBag.ErrorMessage = "Error Calling Graph API.";
                return(View("Error"));
            }
            catch
            {
                ViewBag.ErrorMessage = "Error Calling Graph API.";
                return(View("Error"));
            }
        }
Esempio n. 20
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            //// calculate something for us to return
            //int length = (activity.Text ?? string.Empty).Length;

            //// return our reply to the user
            //await context.PostAsync($"You sent {activity.Text} which was {length} characters");

            if (activity.Text == "login")
            {
                // create state (passing data) for OAuth
                var convRef  = context.Activity.ToConversationReference();
                var stateCol = System.Web.HttpUtility.ParseQueryString(string.Empty);
                stateCol["userId"]         = convRef.User.Id;
                stateCol["botId"]          = convRef.Bot.Id;
                stateCol["conversationId"] = convRef.Conversation.Id;
                stateCol["serviceUrl"]     = convRef.ServiceUrl;
                stateCol["channelId"]      = convRef.ChannelId;

                //var uriBuilder = new UriBuilder(ConfigurationManager.AppSettings["OAuthCallbackUrl"]);
                //var query = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
                //query["userId"] = convRef.User.Id;
                //query["botId"] = convRef.Bot.Id;
                //query["conversationId"] = convRef.Conversation.Id;
                //query["serviceUrl"] = convRef.ServiceUrl;
                //query["channelId"] = convRef.ChannelId;
                //uriBuilder.Query = query.ToString();
                //var redirectUrl = uriBuilder.ToString();

                // create Azure AD signin context
                var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
                var authUri     = authContext.GetAuthorizationRequestUrlAsync(
                    "https://outlook.office365.com/",
                    ConfigurationManager.AppSettings["ClientId"],
                    new Uri(ConfigurationManager.AppSettings["OAuthCallbackUrl"]),
                    UserIdentifier.AnyUser,
                    "&state=" + System.Web.HttpUtility.UrlEncode(stateCol.ToString()));

                // show SignIn card (setting oauth sign-in url to SignIn card)
                var reply = context.MakeMessage();
                reply.Text = "Authentication Required";
                reply.Attachments.Add(SigninCard.Create(
                                          "Login",
                                          "Please login to Office 365",
                                          authUri.Result.ToString()).ToAttachment());
                await context.PostAsync(reply);
            }
            else if (activity.Text == "get mail")
            {
                string accessToken = string.Empty;

                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    var dataStore = scope.Resolve <IBotDataStore <BotData> >();
                    var convRef   = context.Activity.ToConversationReference();
                    var address   = new Microsoft.Bot.Builder.Dialogs.Address
                                    (
                        botId: convRef.Bot.Id,
                        channelId: convRef.ChannelId,
                        userId: convRef.User.Id,
                        conversationId: convRef.Conversation.Id,
                        serviceUrl: convRef.ServiceUrl
                                    );
                    var userData = await dataStore.LoadAsync(
                        address,
                        BotStoreType.BotUserData,
                        CancellationToken.None);

                    accessToken = userData.GetProperty <string>("AccessToken");
                }

                if (string.IsNullOrEmpty(accessToken))
                {
                    await context.PostAsync("Not logging-in (type \"login\")");
                }
                else
                {
                    // Get recent 10 e-mail from Office 365
                    HttpClient cl           = new HttpClient();
                    var        acceptHeader =
                        new MediaTypeWithQualityHeaderValue("application/json");
                    cl.DefaultRequestHeaders.Accept.Add(acceptHeader);
                    cl.DefaultRequestHeaders.Authorization
                        = new AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage httpRes =
                        await cl.GetAsync("https://outlook.office365.com/api/v1.0/me/messages?$orderby=DateTimeSent%20desc&$top=10&$select=Subject,From");

                    if (httpRes.IsSuccessStatusCode)
                    {
                        var     strRes = httpRes.Content.ReadAsStringAsync().Result;
                        JObject jRes   = await httpRes.Content.ReadAsAsync <JObject>();

                        JArray jValue = (JArray)jRes["value"];
                        foreach (JObject jItem in jValue)
                        {
                            string sub = $"Subject={((JValue)jItem["Subject"]).Value}";
                            sub = sub.Replace('<', ' ').Replace('>', ' ').Replace('[', ' ').Replace(']', ' ');
                            await context.PostAsync(sub);
                        }
                    }
                    else
                    {
                        await context.PostAsync("Failed to get e-mail.\n\nPlease type \"login\" before you get e-mail.");
                    }
                }
            }
            else if (activity.Text == "revoke")
            {
                await context.PostAsync("Click [here](https://account.activedirectory.windowsazure.com/), login, and remove this app (Bot with Office 365 Authentication Example).");
            }
            else if (activity.Text == "login_succeed")
            {
                await context.PostAsync("You logged in !");
            }
            else
            {
                await context.PostAsync("# Bot Help\n\nType the following command. (You need your Office 365 Exchange Online subscription.)\n\n**login** -- Login to Office 365\n\n**get mail** -- Get your e-mail from Office 365\n\n**revoke** -- Revoke permissions for accessing your e-mail");
            }

            context.Wait(MessageReceivedAsync);
        }