示例#1
0
 public static async Task<string> GetAccessToken(this IBotContext context, string resourceId)
 {
     AuthResult authResult;
     if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
     {
         try
         {
             InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache);
             var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, resourceId);
             authResult.AccessToken = result.AccessToken;
             authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
             authResult.TokenCache = tokenCache.Serialize();
             context.StoreAuthResult(authResult);
         }
         catch (Exception ex)
         {
             Trace.TraceError("Failed to renew token: " + ex.Message);
             await context.PostAsync("Your credentials expired and could not be renewed automatically!");
             await context.Logout();
             return null;
         }
         return authResult.AccessToken;
     }
     return null;
 }
示例#2
0
        private async Task LogIn(IDialogContext context, IMessageActivity msg, string resourceId)
        {
            try
            {
                string token = await context.GetAccessToken(resourceId);

                if (string.IsNullOrEmpty(token))
                {
                    if (msg.Text != null &&
                        CancellationWords.GetCancellationWords().Contains(msg.Text.ToUpper()))
                    {
                        context.Done(string.Empty);
                    }
                    else
                    {
                        var resumptionCookie = new ResumptionCookie(msg);

                        var authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie, resourceId);

                        await context.PostAsync($"You must be authenticated before you can proceed. Please, click [here]({authenticationUrl}) to log into your account.");

                        context.Wait(this.MessageReceivedAsync);
                    }
                }
                else
                {
                    context.Done(string.Empty);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#3
0
        public static async Task <string> GetADALAccessToken(IBotContext context, AzureADAuthenticationRequest request)
        {
            AuthenticationSettings authenticationSettings = AuthenticationSettings.GetFromAppSettings();
            AuthenticationResult   authenticationResult;

            if (context.UserData.TryGetValue(AuthenticationConstants.AuthResultKey, out authenticationResult))
            {
                try
                {
                    var tokenCache = TokenCacheFactory.SetADALTokenCache(authenticationResult.TokenCache);

                    var result = await AzureActiveDirectoryHelper.GetToken(authenticationResult.UserUniqueId, authenticationSettings, request.ResourceId);

                    authenticationResult.AccessToken       = result.AccessToken;
                    authenticationResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                    authenticationResult.TokenCache        = tokenCache.Serialize();
                    context.StoreAuthResult(authenticationResult);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to renew token: " + ex.Message);
                    await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                    await context.Logout(authenticationSettings);

                    return(null);
                }
                return(authenticationResult.AccessToken);
            }
            return(null);
        }
示例#4
0
            private async void btnActivate_Click(object sender, EventArgs e)
            {
                try
                {
                    string aadToken = AzureActiveDirectoryHelper.GetAADHeaderWithPrompt();

                    this.textBoxRetailServerUrl.Text = this.retailServerUrl;
                    RetailServerContext context        = Helpers.CreateNewRetailServerContext(this.retailServerUrl);
                    ManagerFactory      managerFactory = ManagerFactory.Create(context);

                    managerFactory.Context.SetUserToken(new AADToken(aadToken));
                    managerFactory.Context.SetDeviceToken(null);
                    DeviceActivationResult  result = null;
                    IStoreOperationsManager storeOperationsManager = managerFactory.GetManager <IStoreOperationsManager>();
                    result = await storeOperationsManager.ActivateDevice(this.textBoxDeviceId.Text, this.textBoxRegisterId.Text, "testDevice.DeviceId", forceActivate : true, deviceType : 2 /*testDevice.DeviceType*/);

                    this.AppInfo = new DeviceActivationInformation(this.retailServerUrl, result.Device.TerminalId, result.Device.ChannelName, result.Device.Token, result.Device.DeviceNumber, DateTime.Now);
                    this.mainForm.Log("Activation succeeded.");
                }
                catch (Exception ex)
                {
                    this.mainForm.Log(ex.ToString());
                }

                this.Close();
            }
        public async Task <IActionResult> AzureAdLateralMovement()
        {
            var tenantId = ((ClaimsIdentity)User.Identity)
                           .FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            await CosmosDbHelper.InitializeCosmosDb(tenantId);

            var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);

            var azureActiveDirectoryHelper = new AzureActiveDirectoryHelper(graphClient, HttpContext);

            List <string> lateralMovementDataList = null;

            try
            {
                lateralMovementDataList = await azureActiveDirectoryHelper.RunAzureActiveDirectoryApplication();
            }
            catch (ServiceException e)
            {
                if (e.Error.Code == "TokenNotFound")
                {
                    foreach (var cookie in Request.Cookies.Keys)
                    {
                        Response.Cookies.Delete(cookie);
                    }
                    return(RedirectToAction(nameof(Index), "Home"));
                }
            }
            catch (Exception e)
            {
                return(RedirectToAction(nameof(Index), "Home"));
            }

            return(View(lateralMovementDataList));
        }
示例#6
0
        private async Task LogIn(IDialogContext context, Message msg)
        {
            try
            {
                string token = await context.GetAccessToken();

                if (string.IsNullOrEmpty(token))
                {
                    var resumptionCookie = new ResumptionCookie(msg);

                    var authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie);



                    await context.PostAsync($"You must be authenticated before you can proceed. Please, click [here]({authenticationUrl}) to log into your account.");

                    context.Wait(this.MessageReceivedAsync);
                }
                else
                {
                    context.Done(string.Empty);
                }
            }catch (Exception ex)
            {
                throw ex;
            }
        }
示例#7
0
        private async Task LogIn(IDialogContext context, IMessageActivity msg, string[] scopes)
        {
            try
            {
                string token = await context.GetAccessToken(scopes);

                if (string.IsNullOrEmpty(token))
                {
                    if (msg.Text != null &&
                        CancellationWords.GetCancellationWords().Contains(msg.Text.ToUpper()))
                    {
                        context.Done(string.Empty);
                    }
                    else
                    {
                        var resumptionCookie = new ResumptionCookie(msg);

                        var authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie, scopes);

                        if (msg.ChannelId == "skype")
                        {
                            IMessageActivity response = context.MakeMessage();
                            response.Recipient = msg.From;
                            response.Type      = "message";

                            response.Attachments = new List <Attachment>();
                            List <CardAction> cardButtons = new List <CardAction>();
                            CardAction        plButton    = new CardAction()
                            {
                                Value = authenticationUrl,
                                Type  = "signin",
                                Title = "Authentication Required"
                            };

                            cardButtons.Add(plButton);
                            SigninCard plCard = new SigninCard(this.prompt, new List <CardAction>()
                            {
                                plButton
                            });
                            Attachment plAttachment = plCard.ToAttachment();
                            response.Attachments.Add(plAttachment);
                            await context.PostAsync(response);
                        }
                        else
                        {
                            await context.PostAsync(this.prompt + "[Click here](" + authenticationUrl + ")");
                        }
                        context.Wait(this.MessageReceivedAsync);
                    }
                }
                else
                {
                    context.Done(string.Empty);
                }
            }catch (Exception ex)
            {
                throw ex;
            }
        }
示例#8
0
        public static async Task <string> GetAccessToken(this IBotContext context, string resourceId)
        {
            AuthResult authResult;

            if (context.Activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
            {
                string token = null;
                if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
                {
                    //we have credential
                }
                else
                {
                    token = GetCortanaAccessToken(context);
                    var jwt = new JwtSecurityToken(token);
                    if (authResult == null)
                    {
                        authResult = new AuthResult();
                    }

                    authResult.AccessToken = token;
                    long tick = long.MinValue;
                    long.TryParse(jwt.Payload.Claims.Where(c => c.Type.Equals("exp", StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault()?.Value, out tick);
                    authResult.ExpiresOnUtcTicks = tick;
                    InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(Encoding.ASCII.GetBytes(token));
                    authResult.TokenCache = tokenCache.Serialize();
                    context.StoreAuthResult(authResult);
                }
                return(authResult.AccessToken);
            }
            else
            {
                if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
                {
                    try
                    {
                        InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache);
                        var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, resourceId);

                        authResult.AccessToken       = result.AccessToken;
                        authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                        authResult.TokenCache        = tokenCache.Serialize();
                        context.StoreAuthResult(authResult);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Failed to renew token: " + ex.Message);
                        await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                        await context.Logout();

                        return(null);
                    }
                    return(authResult.AccessToken);
                }
                return(null);
            }
        }
示例#9
0
        public static async Task <string> GetAlias(this IBotContext context)
        {
            AuthResult authResult;
            string     validated = null;

            if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult) &&
                context.UserData.TryGetValue(ContextConstants.MagicNumberValidated, out validated) &&
                validated == "true")
            {
                try
                {
                    if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                    {
                        InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache);
                        var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, AuthSettings.Scopes);

                        authResult.AccessToken       = result.AccessToken;
                        authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                        authResult.TokenCache        = tokenCache.Serialize();
                        authResult.Alias             = result.Alias;
                        context.StoreAuthResult(authResult);
                    }
                    else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new NotImplementedException();
                    }
                    else if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                    {
                        InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache);
                        var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]);

                        authResult.AccessToken       = result.AccessToken;
                        authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                        authResult.TokenCache        = tokenCache.Serialize();
                        authResult.Alias             = result.Alias;
                        context.StoreAuthResult(authResult);
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to renew token: " + ex.Message);
                    await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                    await context.Logout();

                    return(null);
                }
                return(authResult.Alias.Split('@')[0]);
            }

            return(null);
        }
        /// <summary>
        /// Checks if we are able to get an access token. If not, we prompt for a login
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        protected virtual async Task CheckForLogin(IDialogContext context, IMessageActivity msg)
        {
            try
            {
                string token;
                if (resourceId != null)
                {
                    token = await context.GetAccessToken(resourceId);
                }
                else
                {
                    token = await context.GetAccessToken(scopes);
                }

                if (string.IsNullOrEmpty(token))
                {
                    if (msg.Text != null &&
                        CancellationWords.GetCancellationWords().Contains(msg.Text.ToUpper()))
                    {
                        context.Done(string.Empty);
                    }
                    else
                    {
                        var resumptionCookie = new ResumptionCookie(msg);

                        string authenticationUrl;
                        if (resourceId != null)
                        {
                            authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie, resourceId);
                        }
                        else
                        {
                            authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie, scopes);
                        }

                        await PromptToLogin(context, msg, authenticationUrl);

                        context.Wait(this.MessageReceivedAsync);
                    }
                }
                else
                {
                    context.Done(string.Empty);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#11
0
        public static async Task <string> GetAccessToken(this IBotContext context, string[] scopes)
        {
            AuthResult authResult;

            if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
            {
                try
                {
                    if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                    {
                        InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache);

                        var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, scopes);

                        authResult.AccessToken       = result.AccessToken;
                        authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                        authResult.TokenCache        = tokenCache.Serialize();

                        context.StoreAuthResult(authResult);
                    }
                    else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new NotImplementedException();
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to renew token: " + ex.Message);

                    await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                    await context.Logout();

                    return(null);
                }


                return(authResult.AccessToken);
            }

            return(null);
        }
示例#12
0
        public static async Task <object> HandleOAuthCallback(HttpRequestMessage req, uint maxWriteAttempts)
        {
            try
            {
                var queryParams = req.RequestUri.ParseQueryString();

                if (req.Method != HttpMethod.Post)
                {
                    throw new ArgumentException("The OAuth postback handler only supports POST requests.");
                }

                var formData = await req.Content.ReadAsFormDataAsync();

                string stateStr = formData["state"];
                string code     = formData["code"];

                var resumptionCookie = UrlToken.Decode <ResumptionCookie>(stateStr);
                var message          = resumptionCookie.GetMessage();

                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    AuthenticationSettings authSettings = AuthenticationSettings.GetFromAppSettings();

                    var client = scope.Resolve <IConnectorClient>();
                    AuthenticationResult authenticationResult = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, authSettings);

                    IStateClient sc = scope.Resolve <IStateClient>();

                    //IMPORTANT: DO NOT REMOVE THE MAGIC NUMBER CHECK THAT WE DO HERE. THIS IS AN ABSOLUTE SECURITY REQUIREMENT
                    //REMOVING THIS WILL REMOVE YOUR BOT AND YOUR USERS TO SECURITY VULNERABILITIES.
                    //MAKE SURE YOU UNDERSTAND THE ATTACK VECTORS AND WHY THIS IS IN PLACE.
                    int  magicNumber     = GenerateRandomNumber();
                    bool writeSuccessful = false;
                    uint writeAttempts   = 0;
                    while (!writeSuccessful && writeAttempts++ < maxWriteAttempts)
                    {
                        try
                        {
                            BotData userData = sc.BotState.GetUserData(message.ChannelId, message.From.Id);
                            userData.SetProperty(AuthenticationConstants.AuthResultKey, authenticationResult);
                            userData.SetProperty(AuthenticationConstants.MagicNumberKey, magicNumber);
                            userData.SetProperty(AuthenticationConstants.MagicNumberValidated, "false");
                            sc.BotState.SetUserData(message.ChannelId, message.From.Id, userData);
                            writeSuccessful = true;
                        }
                        catch (HttpOperationException)
                        {
                            writeSuccessful = false;
                        }
                    }
                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    if (!writeSuccessful)
                    {
                        message.Text = String.Empty; // fail the login process if we can't write UserData
                        await Conversation.ResumeAsync(resumptionCookie, message);

                        resp.Content = new StringContent("<html><body>Could not log you in at this time, please try again later</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    }
                    else
                    {
                        await Conversation.ResumeAsync(resumptionCookie, message);

                        resp.Content = new StringContent($"<html><body>Almost done! Please copy this number and paste it back to your chat so your authentication can complete:<br/> <h1>{magicNumber}</h1>.</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    }
                    return(resp);
                }
            }
            catch (Exception ex)
            {
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
示例#13
0
        public async Task <HttpResponseMessage> OAuthCallback(
            [FromUri] string code,
            [FromUri] string state,
            CancellationToken cancellationToken)
        {
            try
            {
                var    queryParams = state;
                object tokenCache  = null;
                if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                {
                    tokenCache = new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache();
                }
                else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                {
                    tokenCache = new Microsoft.Identity.Client.TokenCache();
                }
                else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                {
                }

                var resumptionCookie = UrlToken.Decode <ResumptionCookie>(queryParams);
                // Create the message that is send to conversation to resume the login flow
                var message = resumptionCookie.GetMessage();

                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    var        client     = scope.Resolve <IConnectorClient>();
                    AuthResult authResult = null;
                    if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                    {
                        // Exchange the Auth code with Access token
                        var token = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, (Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache) tokenCache);

                        authResult = token;
                    }
                    else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                    {
                        // Exchange the Auth code with Access token
                        var token = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, (Microsoft.Identity.Client.TokenCache) tokenCache, Models.AuthSettings.Scopes);

                        authResult = token;
                    }
                    else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                    {
                    }

                    IStateClient sc = scope.Resolve <IStateClient>();

                    //IMPORTANT: DO NOT REMOVE THE MAGIC NUMBER CHECK THAT WE DO HERE. THIS IS AN ABSOLUTE SECURITY REQUIREMENT
                    //REMOVING THIS WILL REMOVE YOUR BOT AND YOUR USERS TO SECURITY VULNERABILITIES.
                    //MAKE SURE YOU UNDERSTAND THE ATTACK VECTORS AND WHY THIS IS IN PLACE.
                    int  magicNumber     = GenerateRandomNumber();
                    bool writeSuccessful = false;
                    uint writeAttempts   = 0;
                    while (!writeSuccessful && writeAttempts++ < MaxWriteAttempts)
                    {
                        try
                        {
                            BotData userData = sc.BotState.GetUserData(message.ChannelId, message.From.Id);
                            userData.SetProperty(ContextConstants.AuthResultKey, authResult);
                            userData.SetProperty(ContextConstants.MagicNumberKey, magicNumber);
                            userData.SetProperty(ContextConstants.MagicNumberValidated, "false");
                            sc.BotState.SetUserData(message.ChannelId, message.From.Id, userData);
                            writeSuccessful = true;
                        }
                        catch (HttpOperationException)
                        {
                            writeSuccessful = false;
                        }
                    }
                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    if (!writeSuccessful)
                    {
                        message.Text = String.Empty; // fail the login process if we can't write UserData
                        await Conversation.ResumeAsync(resumptionCookie, message);

                        resp.Content = new StringContent("<html><body>Could not log you in at this time, please try again later</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    }
                    else
                    {
                        await Conversation.ResumeAsync(resumptionCookie, message);

                        resp.Content = new StringContent($"<html><body>Almost done! Please copy this number and paste it back to your chat so your authentication can complete:<br/> <h1>{magicNumber}</h1>.</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    }
                    return(resp);
                }
            }
            catch (Exception ex)
            {
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
示例#14
0
        static void Main(string[] args)
        {
            var settingsReader = ConfigurationManager.AppSettings;
            var aadConfig      = new AzureActiveDirectoryConfig();

            //Get Azure Active Directory Configuration form App Settings
            try{
                aadConfig.azureSubscriptionID = settingsReader["subscriptionID"];
                aadConfig.aadApplicationName  = settingsReader["ActiveDirectoryApplicationName"];
                aadConfig.aadRedirectURL      = settingsReader["ActiveDirectoryApplicationRedirect"];
                aadConfig.addClientID         = settingsReader["ActiveDirectoryClientID"];
                aadConfig.addTenant           = settingsReader["ActiveDirectoryadTenant"];
                aadConfig.aadResourceURI      = settingsReader["ActiveDirectoryResourceUri"];
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Source);
            }


            //Authenticates ARM websites client
            var ARMClient = new AzureActiveDirectoryHelper(aadConfig);

            //Sets the Resource Group to use for samples
            Console.Write("Resource Group:");
            var resourceGroup = Console.ReadLine();

            //Initialize the Server Farm Samples
            var webHostingPlanSample = new ARM_WebHostingPlan_Sample();

            webHostingPlanSample.client = ARMClient.client;
            //Initialize the Server Farm Samples
            var websiteSample = new ARM_websites_Sample();

            websiteSample.client = ARMClient.client;

            var operation = 0;
            var mainMenu  = true;

            while (mainMenu)
            {
                Console.Clear();
                Console.WriteLine("...::Select Samples::...");
                Console.WriteLine("1) Web Hosting Plan Operations");
                Console.WriteLine("2) Website Operations");
                Console.WriteLine("0) Quit");

                if (int.TryParse(Console.ReadLine(), out operation))
                {
                    switch (operation)
                    {
                    case 1:
                        var webHostingPlanmMenu = true;
                        while (webHostingPlanmMenu)
                        {
                            webHostingPlanmMenu = webHostingPlanSample.webHostingPlanOperations(resourceGroup);
                        }

                        break;

                    case 2:
                        var websiteMenu = true;
                        while (websiteMenu)
                        {
                            websiteMenu = websiteSample.webSitesOperations(resourceGroup);
                        }
                        break;

                    case 0:
                        mainMenu = false;
                        Console.Clear();
                        Console.Write("..::GOODBYE::..");
                        Thread.Sleep(2000);
                        break;

                    default:
                        Console.Clear();
                        Console.Write("Operation Not recognized:");
                        break;
                    }
                }
                else
                {
                    Console.Clear();
                    Console.Write("Operation Not recognized:");
                }
            }
        }
示例#15
0
        public async Task <HttpResponseMessage> OAuthCallback([FromUri] string code, [FromUri] string state)
        {
            try
            {
                object tokenCache = null;
                if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                {
                    tokenCache = new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache();
                }
                else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                {
                    tokenCache = new Microsoft.Identity.Client.TokenCache();
                }
                else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                {
                }

                // Get the resumption cookie
                var resumptionCookie = UrlToken.Decode <ResumptionCookie>(state);
                // Create the message that is send to conversation to resume the login flow
                var message = resumptionCookie.GetMessage();

                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    var client = scope.Resolve <IConnectorClient>();

                    AuthResult authResult = null;

                    if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                    {
                        // Exchange the Auth code with Access token
                        var token = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, (Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache) tokenCache);

                        authResult = token;
                    }
                    else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                    {
                        //TODO: Scopes definition here
                        // Exchange the Auth code with Access token
                        var token = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, (Microsoft.Identity.Client.TokenCache) tokenCache, new string[] { "User.Read" });

                        authResult = token;
                    }
                    else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                    {
                    }

                    var reply = await Conversation.ResumeAsync(resumptionCookie, message);

                    var data = await client.Bots.GetPerUserConversationDataAsync(resumptionCookie.BotId, resumptionCookie.ConversationId, resumptionCookie.UserId);

                    reply.SetBotUserData(ContextConstants.AuthResultKey, authResult);
                    int magicNumber = GenerateRandomNumber();
                    reply.SetBotUserData(ContextConstants.MagicNumberKey, magicNumber);
                    reply.SetBotUserData(ContextConstants.MagicNumberValidated, "false");

                    //data.SetProperty(ContextConstants.AuthResultKey, authResult);
                    //data.SetProperty(ContextConstants.MagicNumberKey, magicNumber);
                    //data.SetProperty(ContextConstants.MagicNumberValidated, "false");

                    //await client.Bots.SetUserDataAsync(resumptionCookie.BotId, resumptionCookie.UserId, data);



                    reply.To   = message.From;
                    reply.From = message.To;

                    await client.Messages.SendMessageAsync(reply);

                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    resp.Content = new StringContent($"<html><body>Almost done! Please copy this number and paste it back to your chat so your authentication can complete: {magicNumber}.</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    return(resp);
                }
            }
            catch (Exception ex)
            {
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new InvalidOperationException("Cannot resume!")));
            }
        }
示例#16
0
        public async Task <HttpResponseMessage> OAuthCallback([FromUri] string code, [FromUri] string state, CancellationToken cancellationToken)
        {
            try
            {
                object tokenCache = null;
                if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                {
                    tokenCache = new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache();
                }
                else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                {
                    tokenCache = new Microsoft.Identity.Client.TokenCache();
                }
                else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                {
                }

                // Get the resumption cookie
                var resumptionCookie = UrlToken.Decode <ResumptionCookie>(state);
                // Create the message that is send to conversation to resume the login flow
                var message = resumptionCookie.GetMessage();

                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    var        client     = scope.Resolve <IConnectorClient>();
                    AuthResult authResult = null;
                    if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                    {
                        // Exchange the Auth code with Access token
                        var token = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, (Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache) tokenCache);

                        authResult = token;
                    }
                    else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                    {
                        // Exchange the Auth code with Access token
                        var token = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, (Microsoft.Identity.Client.TokenCache) tokenCache, Models.AuthSettings.Scopes);

                        authResult = token;
                    }
                    else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                    {
                    }

                    IStateClient sc = scope.Resolve <IStateClient>();

                    //IMPORTANT: DO NOT REMOVE THE MAGIC NUMBER CHECK THAT WE DO HERE. THIS IS AN ABSOLUTE SECURITY REQUIREMENT
                    //REMOVING THIS WILL REMOVE YOUR BOT AND YOUR USERS TO SECURITY VULNERABILITIES.
                    //MAKE SURE YOU UNDERSTAND THE ATTACK VECTORS AND WHY THIS IS IN PLACE.
                    var dataBag = scope.Resolve <IBotData>();
                    await dataBag.LoadAsync(cancellationToken);

                    int magicNumber = GenerateRandomNumber();
                    dataBag.UserData.SetValue(ContextConstants.AuthResultKey, authResult);
                    dataBag.UserData.SetValue(ContextConstants.MagicNumberKey, magicNumber);
                    dataBag.UserData.SetValue(ContextConstants.MagicNumberValidated, "false");
                    await dataBag.FlushAsync(cancellationToken);

                    await Conversation.ResumeAsync(resumptionCookie, message);

                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    resp.Content = new StringContent($"<html><body>Almost done! Please copy this number and paste it back to your chat so your authentication can complete: {magicNumber}.</body></html>", System.Text.Encoding.UTF8, @"text/html");
                    return(resp);
                }
            }
            catch (Exception ex)
            {
                // Callback is called with no pending message as a result the login flow cannot be resumed.
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }