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=")); }
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())); }
/// <summary> /// NOTE: this sample does not use the ADAL TokenCache and handles Refresh Tokens manually /// You might consider using TokenCache instead /// </summary> public async Task <ActionResult> Index() { //check for code AuthenticationContext authContext = new AuthenticationContext(TokenHelper.AUTHORITY, false, null); ClientCredential creds = new ClientCredential(TokenHelper.CLIENT_ID, TokenHelper.CLIENT_SECRET); if (!String.IsNullOrEmpty(Request["code"])) { //get the access token using the code var result = await authContext.AcquireTokenByAuthorizationCodeAsync( Request["code"], new Uri($"https://{TokenHelper.HOST_DOMAIN}/AADAuth"), creds, TokenHelper.DISCO_RESOURCE); //save the refresh token var cookie = new HttpCookie("RefreshToken", result.RefreshToken); cookie.Expires = DateTime.Now.AddDays(14); Response.SetCookie(cookie); //redirect to files controller return(RedirectToAction("Sites", "Files")); } else { //try to get a refresh token using access token try { //get token using refresh token var token = await this.HttpContext.GetAccessToken(TokenHelper.DISCO_RESOURCE); if (token == null) { throw new Exception(); } //redirect to files controller return(RedirectToAction("Sites", "Files")); } catch (Exception) { //silent attempt for access token failed...perform code authorization flow var url = authContext.GetAuthorizationRequestURL( TokenHelper.DISCO_RESOURCE, TokenHelper.CLIENT_ID, new Uri($"https://{TokenHelper.HOST_DOMAIN}/AADAuth"), UserIdentifier.AnyUser, "state=somestate"); //redirect to the code authorization flow with AAD return(Redirect(url.ToString())); } } }
public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions() { AuthenticationType = "Cookie", CookieName = "M5NgAuth", CookiePath = "/demo/" }); app.UseWsFederationAuthentication(new Microsoft.Owin.Security.WsFederation.WsFederationAuthenticationOptions() { AuthenticationType = "WSFed", SignInAsAuthenticationType = "Cookie", MetadataAddress = Config.ADFS_MetadataAddress, //(ADFS Metadata URL) Wtrealm = Config.ADFSRealmId, //Relying Party (id in ADFS) //Added redirect to get token for Angular app Notifications = new Microsoft.Owin.Security.WsFederation.WsFederationAuthenticationNotifications() { SecurityTokenValidated = ctx => { var callbackUri = new Uri(Config.LoginCallbackUrl); var ctx2 = new AuthenticationContext(Config.ADFS_URL_adfs, false); var url = ctx2.GetAuthorizationRequestURL(Config.WebApiADFSId, Startup.Config.ADFSWebApiClientId, callbackUri, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, null); //Add cookie to tell /demo/auth/loggedin where to redirect if (!string.IsNullOrWhiteSpace(ctx.AuthenticationTicket.Properties.RedirectUri)) { //TODO: protect cookie ctx.Response.Cookies.Append(Config.RedirectCookieName, ctx.AuthenticationTicket.Properties.RedirectUri, new Microsoft.Owin.CookieOptions() { Domain = Config.AppDomain, Expires = DateTime.UtcNow.AddMinutes(30), Path = "/demo/" }); } ctx.AuthenticationTicket.Properties.RedirectUri = url.AbsoluteUri; return(Task.FromResult(0)); } } }); app.UseActiveDirectoryFederationServicesBearerAuthentication( new Microsoft.Owin.Security.ActiveDirectory.ActiveDirectoryFederationServicesBearerAuthenticationOptions() { TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() { ValidAudience = Config.WebApiADFSId }, MetadataEndpoint = Config.ADFS_MetadataAddress }); }
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())); }
public ActionResult SignIn() { if (string.IsNullOrEmpty(SettingsHelper.ClientId) || string.IsNullOrEmpty(SettingsHelper.ClientSecret)) { ViewBag.Message = "Please set your ClientId and ClientSecret in the web.config"; return(View("Error")); } AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority); // The url in our app that Azure should redirect to after successful signin string redirectUri = Url.Action("Authorize", "Home", null, Request.Url.Scheme); // Generate the parameterized URL for Azure signin Uri authUri = authContext.GetAuthorizationRequestURL(SettingsHelper.O365UnifiedResource, SettingsHelper.ClientId, new Uri(redirectUri), UserIdentifier.AnyUser, null); // Redirect the browser to the Azure signin page return(Redirect(authUri.ToString())); }
public static async Task <string> GetAccessToken() { string signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; string authority = AADInstance + TenantId; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCache(signInUserId)); string accessToken = HttpContext.Current.Session["AccessToken"] as string; #region redirect // if session has expired, access token is null and we need to re-authenticate if (string.IsNullOrEmpty(accessToken)) { try { var authResult = await authContext.AcquireTokenSilentAsync(GraphResourceId, new ClientCredential(ClientId, ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); accessToken = authResult.AccessToken; HttpContext.Current.Session["AccessToken"] = accessToken; } catch (Exception ex) { Debug.WriteLine(ex.Message); // Generate the parameterized URL for Azure login. Uri authUri = authContext.GetAuthorizationRequestURL( GraphResourceId, ClientId, new Uri(RedirectUri), UserIdentifier.AnyUser, null); // Signout and re-signing HttpContext.Current.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } } #endregion return(accessToken); }
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); Uri authUri = authContext.GetAuthorizationRequestURL( Settings.O365UnifiedAPIResource, Settings.ClientId, loginRedirectUri, UserIdentifier.AnyUser, null); return(Redirect(authUri.ToString())); }
/// <summary> /// Implement the OPENID authentication and get the access token to access SP site. /// </summary> /// <param name="app"></param> public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, 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.GetAuthorizationRequestURL(sharePointUrl, clientId, consentRedirectUrl, userIdentifier, "prompt=admin_consent").ToString(); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, redirectUrl, credential, resourceId); AuthenticationHelper.token = result.AccessToken; AuthenticationResult spResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUrl, credential, sharePointUrl); AuthenticationHelper.sharePointToken = spResult.AccessToken; return(Task.FromResult(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)); }
/// <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")); } } }
/// <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)); }
/// <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")); } }
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()); }