public ActionResult Conectar()
        {
            var authenticationContext = new AuthenticationContext(authority);

            var url = authenticationContext.GetAuthorizationRequestURL(resource, clientId, new Uri(redirectUrl), UserIdentifier.AnyUser, null);

            //var accessToken = authenticationContext.(resource, new ClientCredential(clientId, clientSecret)).AccessToken;

            return Redirect(url.ToString());
        }
Exemplo n.º 2
0
        public ActionResult SignIn()
        {
            // Create new authentication context
            var authContext = new AuthenticationContext(Settings.Authority);

            // The URL where Azure redirects to after successful login
            Uri loginRedirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

            // Parameterized URL for Azure login
            Uri authUri = authContext.GetAuthorizationRequestURL(Settings.GraphUri, Settings.ClientId, loginRedirectUri, UserIdentifier.AnyUser, null);

            // Redirect to login page, then come back to the Authorize method
            return Redirect(authUri.ToString());
        }
Exemplo n.º 3
0
        public ActionResult Login()
        {
            if (string.IsNullOrEmpty(Settings.ClientId) || string.IsNullOrEmpty(Settings.ClientSecret))
            {
                ViewBag.Message = "Please set your client ID and client secret in the Web.config file";
                return View();
            }

            var authContext = new AuthenticationContext(Settings.AzureADAuthority);

            // Generate the parameterized URL for Azure login.
            Uri authUri = authContext.GetAuthorizationRequestURL(
                Settings.O365UnifiedAPIResource,
                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());
        }
Exemplo n.º 4
0
        // GET: Discovery
        public ActionResult Index(string code)
        {
            // Where do we send auth requests to?
            AuthenticationContext authContext = new AuthenticationContext(
                  ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
                  true);

            // wrapper for the ip and password for this applicaiton
            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            Uri redirectUri = authContext.GetAuthorizationRequestURL(
                discoResource, // Where the discovery service is
                creds.ClientId, // This identifies the application
                new Uri(Request.Url.AbsoluteUri.Split('?')[0]), // Redirect URL
                UserIdentifier.AnyUser,
                string.Empty);

            return Redirect(redirectUri.ToString()); // Redirect to the login page



            List<ViewDiscovery> discoveries = new List<ViewDiscovery>(){
                new ViewDiscovery(){
                    Capability = "Contacts",
                    EndpointUri = contactsDisco.ServiceEndpointUri.OriginalString,
                    ResourceId = contactsDisco.ServiceResourceId,
                    Version = contactsDisco.ServiceApiVersion
                },
                new ViewDiscovery(){
                    Capability = "My Files",
                    EndpointUri = filesDisco.ServiceEndpointUri.OriginalString,
                    ResourceId = filesDisco.ServiceApiVersion
                }
            };

            return View(discoveries);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Use the DiscoveryClient to get the Contacts and Files endpoints
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Index(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            DiscoveryClient disco = Helpers.GetFromCache("DiscoveryClient") as DiscoveryClient;

            //Redirect to login page if we do not have an 
            //authorization code for the Discovery service
            if (disco == null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    discoResource,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create a DiscoveryClient using the authorization code
            if (disco == null && code != null)
            {

                disco = new DiscoveryClient(new Uri(discoEndpoint), async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

            }

            //Discover required capabilities
            CapabilityDiscoveryResult contactsDisco = await disco.DiscoverCapabilityAsync("Contacts");
            CapabilityDiscoveryResult filesDisco = await disco.DiscoverCapabilityAsync("MyFiles");

            Helpers.SaveInCache("ContactsDiscoveryResult", contactsDisco);
            Helpers.SaveInCache("FilesDiscoveryResult", filesDisco);

            List<MyDiscovery> discoveries = new List<MyDiscovery>(){
                new MyDiscovery(){
                    Capability = "Contacts",
                    EndpointUri = contactsDisco.ServiceEndpointUri.OriginalString,
                    ResourceId = contactsDisco.ServiceResourceId,
                    Version = contactsDisco.ServiceApiVersion
                },
                new MyDiscovery(){
                    Capability = "My Files",
                    EndpointUri = filesDisco.ServiceEndpointUri.OriginalString,
                    ResourceId = filesDisco.ServiceResourceId,
                    Version = filesDisco.ServiceApiVersion
                }
            };

            return View(discoveries);

        }
Exemplo n.º 6
0
        /// <summary>
        /// Display a form for creating a new Project
        /// </summary>
        /// <param name="submitModel">The new project data submitted from the form</param>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Projects(ViewModel submitModel, string code)
        {
            //If the New Project form needs to be displayed
            if (submitModel.Project == null && code == null)
            {
                ViewModel formModel = new ViewModel();
                formModel.Contacts = Helpers.GetFromCache("ContactList") as List<MyContact>;
                formModel.Files = Helpers.GetFromCache("FileList") as List<MyFile>;
                return View(formModel);
            }
            // A new project was submitted
            else
            {
                if (submitModel.Project != null)
                {
                    Helpers.SaveInCache("SubmitModel", submitModel);
                }

                AuthenticationContext authContext = new AuthenticationContext(
                   ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
                   true);

                ClientCredential creds = new ClientCredential(
                    ConfigurationManager.AppSettings["ida:ClientID"],
                    ConfigurationManager.AppSettings["ida:Password"]);

                //Get an authorization code, if necessary
                if (code == null)
                {
                    Uri redirectUri = authContext.GetAuthorizationRequestURL(
                        spSite,
                        creds.ClientId,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        UserIdentifier.AnyUser,
                        string.Empty);

                    return Redirect(redirectUri.ToString());
                }
                else
                {
                    //Get the access token
                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    string accessToken = authResult.AccessToken;

                    //Build SharePoint RESTful API endpoint for the list items
                    StringBuilder requestUri = new StringBuilder()
                      .Append(spSite)
                      .Append("/_api/web/lists/getbyTitle('Research Projects')/items");

                    //Create an XML message with the new project data
                    //This message will be POSTED to the SharePoint API endpoint
                    XNamespace atom = "http://www.w3.org/2005/Atom";
                    XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
                    XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

                    submitModel = Helpers.GetFromCache("SubmitModel") as ViewModel;
                    string description = (Helpers.GetFromCache("FileList") as List<MyFile>).Where(f => f.Url == submitModel.Project.DocumentLink).First().Name;
                    string url = submitModel.Project.DocumentLink;
                    string title = submitModel.Project.Title;
                    string owner = submitModel.Project.Owner;

                    XElement message = new XElement(atom + "entry",
                        new XAttribute(XNamespace.Xmlns + "d", d),
                        new XAttribute(XNamespace.Xmlns + "m", m),
                        new XElement(atom + "category", new XAttribute("term", "SP.Data.Research_x0020_ProjectsListItem"), new XAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme")),
                        new XElement(atom + "content", new XAttribute("type", "application/xml"),
                            new XElement(m + "properties",
                                new XElement(d + "Statement", new XAttribute(m + "type", "SP.FieldUrlValue"),
                                    new XElement(d + "Description", description),
                                    new XElement(d + "Url", url)),
                                new XElement(d + "Title", title),
                                new XElement(d + "Owner", owner))));

                    StringContent requestData = new StringContent(message.ToString());

                    //POST the data to the endpoint
                    HttpClient client = new HttpClient();
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri.ToString());
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    requestData.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/atom+xml");
                    request.Content = requestData;
                    HttpResponseMessage response = await client.SendAsync(request);

                    //Show the Finished screen
                    return RedirectToAction("Finished");
                }
            }


        }
Exemplo n.º 7
0
        /// <summary>
        /// Use the SharePointClient to get OneDrive for Business Files
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Files(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            //Get the discovery information that was saved earlier
            CapabilityDiscoveryResult cdr = Helpers.GetFromCache("FilesDiscoveryResult") as CapabilityDiscoveryResult;

            //Get a client, if this page was already visited
            SharePointClient sharepointClient = Helpers.GetFromCache("SharePointClient") as SharePointClient;

            //Get an authorization code, if needed
            if (sharepointClient == null && cdr != null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    cdr.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create the SharePointClient
            if (sharepointClient == null && cdr != null && code != null)
            {

                sharepointClient = new SharePointClient(cdr.ServiceEndpointUri, async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

                Helpers.SaveInCache("SharePointClient", sharepointClient);
            }

            //Get the files
            var filesResults = await sharepointClient.Files.ExecuteAsync();

            var fileList = new List<MyFile>();

            foreach (var file in filesResults.CurrentPage.Where(f => f.Name != "Shared with Everyone").OrderBy(e => e.Name))
            {
                fileList.Add(new MyFile
                {
                    Id = file.Id,
                    Name = file.Name,
                    Url = file.WebUrl
                });
            }

            //Save the files
            Helpers.SaveInCache("FileList", fileList);

            //Show the files
            return View(fileList);

        }
Exemplo n.º 8
0
        /// <summary>
        /// Use the OutlookServicesClient to get Exchange contacts
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Contacts(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            //Get the discovery information that was saved earlier
            CapabilityDiscoveryResult cdr = Helpers.GetFromCache("ContactsDiscoveryResult") as CapabilityDiscoveryResult;

            //Get a client, if this page was already visited
            OutlookServicesClient outlookClient = Helpers.GetFromCache("OutlookClient") as OutlookServicesClient;

            //Get an authorization code if needed
            if (outlookClient == null && cdr != null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    cdr.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create the OutlookServicesClient
            if (outlookClient == null && cdr != null && code != null)
            {

                outlookClient = new OutlookServicesClient(cdr.ServiceEndpointUri, async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

                Helpers.SaveInCache("OutlookClient", outlookClient);
            }

            //Get the contacts
            var contactsResults = await outlookClient.Me.Contacts.ExecuteAsync();
            List<MyContact> contactList = new List<MyContact>();

            foreach (var contact in contactsResults.CurrentPage.OrderBy(c => c.Surname))
            {
                contactList.Add(new MyContact
                {
                    Id = contact.Id,
                    GivenName = contact.GivenName,
                    Surname = contact.Surname,
                    DisplayName = contact.Surname + ", " + contact.GivenName,
                    CompanyName = contact.CompanyName,
                    EmailAddress1 = contact.EmailAddresses.FirstOrDefault().Address,
                    BusinessPhone1 = contact.BusinessPhones.FirstOrDefault(),
                    HomePhone1 = contact.HomePhones.FirstOrDefault()
                });
            }

            //Save the contacts
            Helpers.SaveInCache("ContactList", contactList);

            //Show the contacts
            return View(contactList);

        }
        //
        // GET: /UserProfile/
        public async Task<ActionResult> Index(string authError)
        {
            UserProfile profile = null;
            AuthenticationContext authContext = null;
            AuthenticationResult result = null;
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;

            try
            {
                ClientCredential credential = new ClientCredential(Startup.clientId, Startup.appKey);
                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 = authContext.GetAuthorizationRequestURL(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);
                }

                result = authContext.AcquireTokenSilent(Startup.graphResourceId, credential, UserIdentifier.AnyUser);
            }
            catch (AdalException e)
            {
                if (e.ErrorCode == "failed_to_acquire_token_silently") {
                    
                    // 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 = GenerateState(userObjectID, Request.Url.ToString());

                    ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(Startup.graphResourceId, Startup.clientId, redirectUri, UserIdentifier.AnyUser, state == null ? null : "&state=" + state);

                    return View(profile);
                }

                ViewBag.ErrorMessage = "Error while Acquiring Token from Cache.";
                return View("Error");
            
            }

            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 = authContext.GetAuthorizationRequestURL(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");
            }
        }
        // GET: Files
        public async Task<ActionResult> Index(string authError)
        {
            List<MyFile> myFiles = new List<MyFile>();

            AuthenticationContext authContext = null;
            AuthenticationResult result = null;
            CapabilityDiscoveryResult filesCapabilityDiscoveryResult = null;
            DiscoveryClient discoveryClient = null;
            SharePointClient spClient = null;

            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;

            ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);

            try
            {
                authContext = new AuthenticationContext(SettingsHelper.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 = authContext.GetAuthorizationRequestURL(SettingsHelper.DiscoveryServiceResourceId,
                        SettingsHelper.ClientId,
                        redirectUri,
                        UserIdentifier.AnyUser,
                        state == null ? null : "&state=" + state);

                    ViewBag.ErrorMessage = "UnexpectedError";

                    return View(myFiles);
                }

                // Query Discovery Service to retrieve MyFiles capability result
                result = authContext.AcquireTokenSilent(SettingsHelper.DiscoveryServiceResourceId, credential, UserIdentifier.AnyUser);
                discoveryClient = new DiscoveryClient(() =>
                {
                    return result.AccessToken;
                });
                
            }
            catch (AdalException e)
            {
                if (e.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {

                    // 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.                 
                    ViewBag.ErrorMessage = "AuthorizationRequired";
                    authContext = new AuthenticationContext(SettingsHelper.Authority);
                    Uri redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");

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

                    ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(SettingsHelper.DiscoveryServiceResourceId,
                        SettingsHelper.ClientId,
                        redirectUri,
                        UserIdentifier.AnyUser,
                        state == null ? null : "&state=" + state);

                    return View(myFiles);
                }

                ViewBag.ErrorMessage = "Error while Acquiring Token from Cache.";

                return View("Error");

            }

            try
            {
                ViewBag.Office365User = result.UserInfo.GivenName;

                ActiveDirectoryClient adGraphClient = new ActiveDirectoryClient(SettingsHelper.AADGraphServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.AADGraphResourceId, credential, UserIdentifier.AnyUser);

                        return authResult.AccessToken;
                    });

                var currentUser = await adGraphClient.Users.Where(u => u.ObjectId == result.UserInfo.UniqueId).ExecuteSingleAsync();

                ViewBag.Office365User = String.Format("{0} ({1})",currentUser.DisplayName,currentUser.Mail);

                filesCapabilityDiscoveryResult = await discoveryClient.DiscoverCapabilityAsync("MyFiles");

                // Initialize SharePoint client to query users' files
                spClient = new SharePointClient(filesCapabilityDiscoveryResult.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(filesCapabilityDiscoveryResult.ServiceResourceId, credential, UserIdentifier.AnyUser);

                        return authResult.AccessToken;
                    });
               
                // Query users' files and get the first paged collection
                var filesCollection = await spClient.Files.ExecuteAsync();
                var files = filesCollection.CurrentPage;
                foreach (var file in files)
                {
                    myFiles.Add(new MyFile { Name = file.Name });
                }

                return View(myFiles);
            }
            catch (Exception e)
            {
                ViewBag.ErrorMessage = String.Format("UnexpectedError: {0}", e.Message);

                return View("Error");
            }           
        }
        internal static void GetAuthorizationRequestURLTest(Sts sts)
        {
            var context = new AuthenticationContext(sts.Authority, sts.ValidateAuthority);
            Uri uri = null;

            try
            {
                uri = context.GetAuthorizationRequestURL(null, sts.ValidClientId, sts.ValidDefaultRedirectUri, sts.ValidUserId, "extra=123");
            }
            catch (ArgumentNullException ex)
            {
                Verify.AreEqual(ex.ParamName, "resource");
            }
            
            uri = context.GetAuthorizationRequestURL(sts.ValidResource, sts.ValidClientId, sts.ValidDefaultRedirectUri, sts.ValidUserId, "extra=123");
            Verify.IsNotNull(uri);
            Verify.IsTrue(uri.AbsoluteUri.Contains("login_hint"));
            Verify.IsTrue(uri.AbsoluteUri.Contains("extra=123"));
            uri = context.GetAuthorizationRequestURL(sts.ValidResource, sts.ValidClientId, sts.ValidDefaultRedirectUri, UserIdentifier.AnyUser, null);
            Verify.IsNotNull(uri);
            Verify.IsFalse(uri.AbsoluteUri.Contains("login_hint"));
            Verify.IsFalse(uri.AbsoluteUri.Contains("client-request-id="));
            context.CorrelationId = Guid.NewGuid();
            uri = context.GetAuthorizationRequestURL(sts.ValidResource, sts.ValidClientId, sts.ValidDefaultRedirectUri, sts.ValidUserId, "extra");
            Verify.IsNotNull(uri);
            Verify.IsTrue(uri.AbsoluteUri.Contains("client-request-id="));
        }
Exemplo n.º 12
0
        public async Task<ActionResult> Index(string code)
        {
            List<MyEvent> eventList = new List<MyEvent>();

            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            DiscoveryClient disco = GetFromCache("DiscoveryClient") as DiscoveryClient;
            CapabilityDiscoveryResult eventsDisco =GetFromCache("EventsDiscovery") as CapabilityDiscoveryResult;

            //Redirect to login page if we do not have an 
            //authorization code for the Discovery service
            if (disco == null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    discoResource,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create a DiscoveryClient using the authorization code
            if (disco == null && code != null)
            {

                disco = new DiscoveryClient(new Uri(discoEndpoint), async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

            }

            if (disco != null && code != null & eventsDisco == null)
            {

                //Discover required capabilities
                eventsDisco = await disco.DiscoverCapabilityAsync("Calendar");
                SaveInCache("EventsDiscovery", eventsDisco);

                code = null;

                //Get authorization code for the calendar
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    eventsDisco.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Get the calendar events
            if (disco != null && code != null & eventsDisco != null)
            {
                OutlookServicesClient outlookClient = new OutlookServicesClient(eventsDisco.ServiceEndpointUri, async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

                //Get the events for the next 8 hours
                var eventResults = await (from i in outlookClient.Me.Events
                                          where i.End >= DateTimeOffset.UtcNow && i.End <= DateTimeOffset.UtcNow.AddHours(8)
                                          select i).Take(5).ExecuteAsync();
                var events = eventResults.CurrentPage.OrderBy(e => e.Start);

                foreach (var e in events)
                {
                    eventList.Add(new MyEvent
                    {
                        Id = e.Id,
                        Body = e.Body == null ? string.Empty : e.Body.Content,
                        End = e.End,
                        Location = e.Location == null ? string.Empty : e.Location.DisplayName,
                        Start = e.Start,
                        Subject = e.Subject == null ? string.Empty : e.Subject

                    });
                }

                //cache the events
                SaveInCache("Events", eventList);
            }

            return View();

        }