// GET: MyFiles
        public async Task<ActionResult> Index()
        {
            List<MyFile> myFiles = new List<MyFile>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(AADAppSettings.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(AADAppSettings.DiscoveryServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("MyFiles");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                SharePointClient spClient = new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var filesResult = await spClient.Files.ExecuteAsync();

                do
                {
                    var files = filesResult.CurrentPage.OfType<File>();

                    foreach (var file in files)
                    {
                        myFiles.Add(new MyFile { Name = file.Name });
                    }

                    filesResult = await filesResult.GetNextPageAsync();

                } while (filesResult != null);
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return View(myFiles);
        }
    private async Task<OutlookServicesClient> EnsureClientCreated() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      // discover contact endpoint
      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // create O365 discovery client 
      DiscoveryClient discovery = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);

          return authResult.AccessToken;
        });

      // query discovery service for endpoint for 'calendar' endpoint
      CapabilityDiscoveryResult dcr = await discovery.DiscoverCapabilityAsync("Contacts");

      // create an OutlookServicesclient
      return new OutlookServicesClient(dcr.ServiceEndpointUri,
        async () => {
          var authResult =
            await
              authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, clientCredential, userIdentifier);
          return authResult.AccessToken;
        });
    }
    private async Task InitOneNoteRestConnection() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      // discover onenote endpoint
      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // authenticate with directory service
      var discoClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);
          return authResult.AccessToken;
        });

      // query discovery service for endpoint for onenote endpoint
      var discoCapabilityResult = await discoClient.DiscoverCapabilityAsync("Notes");

      // get details around onedrive endpoint (replace 1.0 with 2.0 for the new REST API)
      _oneNoteResourceId = discoCapabilityResult.ServiceResourceId;
      _oneNoteEndpoint = discoCapabilityResult.ServiceEndpointUri.ToString();
      var accessToken = (await authContext.AcquireTokenSilentAsync(_oneNoteResourceId, clientCredential, userIdentifier)).AccessToken;

      // set the access token on all requests for onenote API
      _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

      return;
    }
        private static async Task<SharePointClient> GetSharePointClient()
        {
            string signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            DiscoveryClient discovery = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

            CapabilityDiscoveryResult capability = await discovery.DiscoverCapabilityAsync(SettingsHelper.Capability);
            SharePointClient client = new SharePointClient(capability.ServiceEndpointUri,
                async () =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(capability.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return authResult.AccessToken;
                });
            return client;
        }
        // GET: Contacts
        public async Task<ActionResult> Index()
        {

            List<MyContact> myContacts = new List<MyContact>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("Contacts");

                OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var contactsResult = await exClient.Me.Contacts.ExecuteAsync();

                do
                {
                    var contacts = contactsResult.CurrentPage;
                    foreach (var contact in contacts)
                    {
                        myContacts.Add(new MyContact { Name = contact.DisplayName });
                    }

                    contactsResult = await contactsResult.GetNextPageAsync();

                } while (contactsResult != null);
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    //handle token acquisition failure
                }
            }


            return View(myContacts);
        }
        public async Task<ActionResult> Index()
        {
            try
            {
                var signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

                var userObjectIdClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
                var userObjectId = userObjectIdClaim != null ? userObjectIdClaim.Value : signedInUserId;

                string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                string authority = string.Format(Startup.AuthorityFormat, tenantId);

                AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserId));

                AuthenticationResult authenticationResult;

                if (Startup.Certificate == null)
                {
                    ClientCredential credential = new ClientCredential(clientId, appKey);
                    authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, credential, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                }
                else
                {
                    ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Startup.Certificate);
                    authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, clientAssertionCertificate, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                }

                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, nugetPublishServiceBaseAddress + "/domains");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    JArray result = JArray.Parse(json);

                    PublishModel model = new PublishModel();
                    foreach (string s in result.Values().Select(jtoken => jtoken.ToString()))
                    {
                        model.Domains.Add(s);
                    }

                    return View(model);
                }
                else
                {
                    return View(new PublishModel { Message = "Unable to load list of domains" });
                }
            }
            catch (AdalSilentTokenAcquisitionException)
            {
                //TODO: this isn't quite right
                HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                return View(new PublishModel { Message = "AuthorizationRequired" });
            }
        }
Example #7
0
        // GET: User
        //public ActionResult Index()
        //{
        // return View();
        //}

        internal static async Task<SharePointClient> EnsureSharePointClientCreatedAsync()
        {
            string _clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            string _clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];

            string _tenantId = ConfigurationManager.AppSettings["ida:TenantID"];
            string _aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string _authority = _aadInstance + _tenantId;

            string _discoverySvcEndpointUriStr = "https://api.office.com/discovery/v1.0/me/";
            Uri _discoverySvcEndpointUri = new Uri(_discoverySvcEndpointUriStr);
            string _discoverySvcResourceId = "https://api.office.com/discovery/";


            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            AuthenticationContext authContext = new AuthenticationContext(_authority, new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(_discoverySvcEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(_discoverySvcResourceId,
                                                                                   new ClientCredential(_clientId,
                                                                                                        _clientSecret),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));
                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("MyFiles");

                return new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                                                                                   new ClientCredential(_clientId,
                                                                                                        _clientSecret),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });
            }
            catch (AdalException exception)
            {
                //Partially handle token acquisition failure here and bubble it up to the controller
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
        public async Task<ActionResult> Sites()
        {
            List<SearchResult> results = new List<SearchResult>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResultDisc = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResultDisc.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("RootSite");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                var authResultSharePoint = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, 
                    new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                var sharePointToken = authResultSharePoint.AccessToken;

                results.Add(new SearchResult
                {
                    Title = "Root Site",
                    Path = dcr.ServiceResourceId,
                });

                var query = "/search/query?querytext='contentclass:sts_site'&trimduplicates=true&rowlimit=50&SelectProperties='WebTemplate,Title,Path,SiteLogo,contentclass'";

                await ExecuteSearchQuery(results, dcr, sharePointToken, query);

            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return View(results);
        }
        internal static async Task<SharePointClient> EnsureSharePointClientCreatedAsync(string capabilityName)
        {
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            //pay attention to the ADALTokenCache in this example
            AuthenticationContext authContext = new AuthenticationContext(
                Constants.Authority, new ADALTokenCache(signInUserId));

            try
            {
                //The discovery client gives us the discovery URL
                DiscoveryClient discClient = new DiscoveryClient(new Uri(Constants.DiscoveryServiceEndpointUri),
                    async () =>
                    {
                        var authResult =
                            await authContext.AcquireTokenSilentAsync(Constants.DiscoveryServiceResourceId,
                            new ClientCredential(Constants.ClientId,
                            Constants.ClientSecret),
                            new UserIdentifier(userObjectId,
                            UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);

                //We can now create a SharePointClient
                return new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(
                            dcr.ServiceResourceId,
                            new ClientCredential(Constants.ClientId,Constants.ClientSecret),
                            new UserIdentifier(userObjectId,UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });
            }
            catch (AdalException exception)
            {
                //Partially handle token acquisition failure here and bubble it up to the controller
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
        public async Task<string> Login(string sharePointSiteUrl, bool forceLogin = false)
        {
            var spUri = new Uri(sharePointSiteUrl);

            string resourceUri = spUri.Scheme + "://" + spUri.Authority;

            ADAL.AuthenticationResult authenticationResult;
 
            try
            {
                authenticationResult = await AuthContext.AcquireTokenSilentAsync(resourceUri, clientId);
            }
            catch (ADAL.AdalSilentTokenAcquisitionException)
            {
                //Console.WriteLine("Silent Async failed. Use prompt instead.");

                try
                {
                    // prevent flashing of login window when credentials are valid
                    var authParam = new ADAL.PlatformParameters(ADAL.PromptBehavior.Never);
                    authenticationResult = await AuthContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), authParam);
                }
                catch (ADAL.AdalException /* e */)
                {
                    //Console.WriteLine(e);

                    var authParam = new ADAL.PlatformParameters(ADAL.PromptBehavior.Auto);
                    authenticationResult = await AuthContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), authParam);

                }
            }


            return authenticationResult.CreateAuthorizationHeader();
        }
        public async Task AcquireTokenSilentServiceErrorTestAsync()
        {
            Sts sts = new AadSts();
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(sts.Authority, sts.ValidResource, sts.ValidClientId, TokenSubjectType.User, "unique_id", "*****@*****.**");
            cache.tokenCacheDictionary[key] = new AuthenticationResult("Bearer", "some-access-token",
                "invalid-refresh-token", DateTimeOffset.UtcNow);

            AuthenticationContext context = new AuthenticationContext(sts.Authority, sts.ValidateAuthority, cache);

            try
            {
                await context.AcquireTokenSilentAsync(sts.ValidResource, sts.ValidClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId));
                Verify.Fail("AdalSilentTokenAcquisitionException was expected");
            }
            catch (AdalSilentTokenAcquisitionException ex)
            {
                Verify.AreEqual(AdalError.FailedToAcquireTokenSilently, ex.ErrorCode);
                Verify.AreEqual(AdalErrorMessage.FailedToRefreshToken, ex.Message);
                Verify.IsNotNull(ex.InnerException);
                Verify.IsTrue(ex.InnerException is AdalException);
                Verify.AreEqual(((AdalException)ex.InnerException).ErrorCode, "invalid_grant");
            }
            catch
            {
                Verify.Fail("AdalSilentTokenAcquisitionException was expected");
            }

        }
        // Get an access token for the given context and resource ID silently. We run this only after the user has already been authenticated.
        private static async Task<string> GetTokenHelperAsync(AuthenticationContext context, string resourceId)
        {
            string accessToken = null;
            AuthenticationResult result = null;

            result = await context.AcquireTokenSilentAsync(resourceId, ClientID);

            if (result.Status == AuthenticationStatus.Success)
            {
                accessToken = result.AccessToken;

                // Store values for logged-in user, tenant ID, and authority, so that
                // they can be re-used if the user re-opens the app without disconnecting.
                App._settings.LoggedInUser = result.UserInfo.UniqueId;
                App._settings.UserEmail= result.UserInfo.DisplayableId;
                App._settings.TenantId = result.TenantId;
                App._settings.LastAuthority = context.Authority;

                return accessToken;
            }
            else
            {
                return null;
            }
        }
    // GET: Discovery
    public async Task<ActionResult> Index()
    {
      // get instance of the authentication context using the token cache we created previously
      var signedInUser = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signedInUser));

      // create credentials for the application
      var appCred = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

      // get user identifier
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
      var userId = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create instance of DiscoveryClient
      var discoveryClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () =>
        {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, appCred, userId);
          return authResult.AccessToken;
        });

      // query discovery service for endpoints
      var capabilitiesResults = await discoveryClient.DiscoverCapabilitiesAsync();

      return View(capabilitiesResults);
    }
    public async Task<ActionResult> Open() {
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      string token = null;
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // get the activation parameters submitted from SharePoint
      ActivationParameters parameters = this.LoadActivationParameters();

      // get access token for unified api
      var authResult = await authContext.AcquireTokenSilentAsync(parameters.ResourceId, clientCredential, userIdentifier);
      token = authResult.AccessToken;

      // get contents of the file in SharePoint
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(parameters.FileGet);
      request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
      Stream responseStream = request.GetResponse().GetResponseStream();
      StreamReader srReader = new StreamReader(responseStream);
      var fileContents = srReader.ReadToEnd();

      // read XML feed
      XmlReader xmlReader = XmlReader.Create(fileContents);
      SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
      xmlReader.Close();

      ViewBag.FeedTitle = feed.Title.Text;
      ViewBag.Posts = feed.Items;
      return View();
    }
    public static async Task<string> GetAccessToken() {
      if (string.IsNullOrEmpty(_accessToken)) {

        // fetch from stuff user claims
        var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

        // discover contact endpoint
        var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
        var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

        // create auth context
        AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority,
          new EfAdalTokenCache(userObjectId));

        // authenticate
        var authResult =
          await
            authContext.AcquireTokenSilentAsync(
              string.Format("https://{0}.sharepoint.com", SettingsHelper.Office365TenantId), clientCredential,
              userIdentifier);

        // obtain access token
        _accessToken = authResult.AccessToken;
      }

      return _accessToken;
    }
        public async static Task<AuthenticationResult> GetTokenAsync(AuthenticationContext ctx, string resourceId)
        {
            ClientCredential credential = new ClientCredential(OfficeSettings.ClientId, OfficeSettings.ClientSecret);
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            UserIdentifier ident = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            var redirectUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

            try
            {
                var result = await ctx.AcquireTokenSilentAsync(resourceId, credential, ident);
                //var result = await ctx.AcquireTokenAsync(resourceId, credential);
                LastAuthority = ctx.Authority;
                return result;
            }
            catch (AdalException)
            {
                ctx.TokenCache.Clear();
                return null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static string GetAccessToken(string resource)
        {
            // get ClaimsPrincipal for current user
              ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current;
              string signedInUserID = currentUserClaims.FindFirst(ClaimTypes.NameIdentifier).Value;
              string tenantID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
              string userObjectID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

              ApplicationDbContext db = new ApplicationDbContext();
              ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID);

              string urlAuthorityRoot = ConfigurationManager.AppSettings["ida:AADInstance"];
              string urlAuthorityTenant = urlAuthorityRoot + tenantID;

              AuthenticationContext authenticationContext =
            new AuthenticationContext(urlAuthorityTenant, userTokenCache);

              Uri uriReplyUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

              string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
              string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
              ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);

              UserIdentifier userIdentifier = new UserIdentifier(userObjectID, UserIdentifierType.UniqueId);

              AuthenticationResult authenticationResult =
            authenticationContext.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier).Result;

              return authenticationResult.AccessToken;
        }
Example #18
0
        private async Task AdalLogin(bool forcePrompt)
        {
            var spUri = new Uri($"{txtSiteFor2FA.Text}");

            string       resourceUri = spUri.Scheme + "://" + spUri.Authority;
            const string clientId    = "9bc3ab49-b65d-410a-85ad-de819febfddc";
            const string redirectUri = "https://oauth.spops.microsoft.com/";

            ADAL.AuthenticationResult authenticationResult;

            if (authContext == null || forcePrompt)
            {
                ADAL.TokenCache cache = new ADAL.TokenCache();
                authContext = new ADAL.AuthenticationContext(AuthorityUri, cache);
            }
            try
            {
                if (forcePrompt)
                {
                    throw new ADAL.AdalSilentTokenAcquisitionException();
                }
                authenticationResult = await authContext.AcquireTokenSilentAsync(resourceUri, clientId);
            }
            catch (ADAL.AdalSilentTokenAcquisitionException)
            {
                authenticationResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always, null), ADAL.UserIdentifier.AnyUser, null, null);
            }

            options.AccessToken = authenticationResult.AccessToken;
            accessTokenObtained = true;
        }
        public string GetAccessToken()
        {
            ApplicationDbContext db = new ApplicationDbContext();
              string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
              string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
              string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
              string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];

              string Authority = aadInstance + tenantId;

              string claimIdName = ClaimTypes.NameIdentifier;
              string claimIdTenantId = "http://schemas.microsoft.com/identity/claims/tenantid";
              string claimIdUserId = "http://schemas.microsoft.com/identity/claims/objectidentifier";

              ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current;

              string signedInUserID = currentUserClaims.FindFirst(claimIdName).Value;
              string tenantID = currentUserClaims.FindFirst(claimIdTenantId).Value;
              string userObjectID = currentUserClaims.FindFirst(claimIdUserId).Value;

              // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
              ClientCredential clientcred = new ClientCredential(clientId, appKey);
              // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
              AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
              AuthenticationResult authenticationResult =
            authenticationContext.AcquireTokenSilentAsync(resource,
                                                      clientcred,
                                                      new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)).Result;
              return authenticationResult.AccessToken;
        }
        internal static async Task<OutlookServicesClient> EnsureOutlookServicesClientCreatedAsync(string capabilityName)
        {

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new NaiveSessionCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId,
                                                                                   new ClientCredential(SettingsHelper.ClientId,
                                                                                                        SettingsHelper.AppKey),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);

                return new OutlookServicesClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                                                                                   new ClientCredential(SettingsHelper.ClientId,
                                                                                                        SettingsHelper.AppKey),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });
            }
            catch (AdalException exception)
            {
                //Handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
        //  The idea of the packages page is that it gets the list of packages from Lucene (from the Search Service)
        //  but when the owner is the current user (if there is a current user), packages owned by him are highlighted.
        //  So far this packages page just gets the list of registrations for which the current user is an owner.

        // GET: Packages
        public async Task<ActionResult> Index()
        {
            try
            {
                string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                string authority = string.Format(aadInstance, tenantId);
                AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserID));

                ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Startup.Certificate);
                AuthenticationResult authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, clientAssertionCertificate, new UserIdentifier(signedInUserID, UserIdentifierType.UniqueId));

                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, nugetSearchServiceBaseAddress + "/query");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);

                HttpResponseMessage response;

                try
                {
                    response = await client.SendAsync(request);
                }
                catch (Exception e)
                {
                    return View("ServiceError", new ServiceErrorModel(e));
                }
                    
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    return View(new PackagesModel(JObject.Parse(json)));
                }
                else
                {
                    string err = await response.Content.ReadAsStringAsync();
                    return View("ServiceError", new ServiceErrorModel(response.StatusCode, err));
                }
            }
            catch (Exception)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";

                return View();
            }
        }
        async Task<ActionResult> Send(string action)
        {
            var signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectIdClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
            var userObjectId = userObjectIdClaim != null ? userObjectIdClaim.Value : signedInUserId;

            string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            string authority = string.Format(Startup.AuthorityFormat, tenantId);

            AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserId));

            AuthenticationResult authenticationResult;

            if (Startup.Certificate == null)
            {
                ClientCredential credential = new ClientCredential(clientId, appKey);
                authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, credential, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
            }
            else
            {
                ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Startup.Certificate);
                authenticationResult = await authContext.AcquireTokenSilentAsync(nugetServiceResourceId, clientAssertionCertificate, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
            }

            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, nugetPublishServiceBaseAddress.TrimEnd('/') + "/tenant/" + action);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);

            HttpResponseMessage response = await client.SendAsync(request);

            string message = null;
            if (response.IsSuccessStatusCode)
            {
                message = "OK";
            }
            else
            {
                JObject publishServiceResponse = JObject.Parse(await response.Content.ReadAsStringAsync());
                message = string.Format("ERROR: {0}", publishServiceResponse["error"].ToString());
            }

            return View(new TenantModel { Message = message });
        }
        public async Task<ActionResult> Open()
        {
            ActivationParameters parameters = this.LoadActivationParameters();

            string test = HttpContext.User.Identity.Name;
            await HttpContext.GetOwinContext().Authentication.AuthenticateAsync(OpenIdConnectAuthenticationDefaults.AuthenticationType);

            //load activation parameters and all the stuff you need to get a token
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            String token = null;
            AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));
            AuthenticationResult authResult = null;
            Session[AADAppSettings.SavedFormDataName] = parameters;

            try
            {
                //grab the token
                authResult = await authContext.AcquireTokenSilentAsync(parameters.ResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                token = authResult.AccessToken;

                //assemble request to get the file
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(parameters.FileGet.Replace("''", "'"));
                request.Headers.Add("Authorization: bearer " + token);
                Stream responseStream = request.GetResponse().GetResponseStream();

                //get the file & load it into a gpx file
                bool complete = gpxUtils.LoadGPXFromStream(responseStream);
                Session[DocumentKey] = gpxUtils;
                if (complete)
                {
                    //set the name of the user, the different coordinates to map out, and the title of the track
                    ViewBag.Name = ClaimsPrincipal.Current.FindFirst(ClaimTypes.GivenName).Value + " " + ClaimsPrincipal.Current.FindFirst(ClaimTypes.Surname).Value;
                    ViewBag.Coordinates = gpxUtils.getPointsFromGPX();
                    ViewBag.Title = gpxUtils.getTitle();
                    return View();
                }
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    return Content(exception.Message);
                }
            }
            catch (Exception exception)
            {
                authContext.TokenCache.Clear();
                return Content(exception.Message);
            }

            return Content("GPX file could not be loaded.<br/>Token: " + token + "<br/> FileGet URL: " + parameters.FileGet);
        }
    public async Task<string> GetTokenForApplication() {
      string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
      string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

      // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
      ClientCredential clientcred = new ClientCredential(clientId, appKey);
      // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
      AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
      AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
      return authenticationResult.AccessToken;
    }
        public static async Task <AuthenticationResult> AcquireTokenSilentAsync(this AuthenticationContext ctx, string resource, string clientId)
        {
            HttpMessageHandlerFactory.UpdateWebProxyNeeded += (sender, args) =>
            {
                args.HttpClient.Proxy = new WebProxy(args.ProxyUrl, true)
                {
                    UseDefaultCredentials = true
                };
            };

            return(await ctx.AcquireTokenSilentAsync(resource, clientId).ConfigureAwait(false));
        }
        private async Task<string> GetGraphAccessTokenAsync()
        {
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

            var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureAdAuthority, new ADALTokenCache(signInUserId));
            var result = await authContext.AcquireTokenSilentAsync(SettingsHelper.AzureAdGraphResourceURL, clientCredential, userIdentifier);
            return result.AccessToken;
        }
 public static async Task<string> GetGraphAccessTokenAsync()
 {
     var AzureAdGraphResourceURL = "https://graph.microsoft.com/";
     var Authority = ConfigurationManager.AppSettings["ida:AADInstance"] + ConfigurationManager.AppSettings["ida:TenantId"];
     var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
     var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
     var clientCredential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientId"], ConfigurationManager.AppSettings["ida:ClientSecret"]);
     var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
     AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signInUserId));
     var result = await authContext.AcquireTokenSilentAsync(AzureAdGraphResourceURL, clientCredential, userIdentifier);
     return result.AccessToken;
 }
        // GET: TodoList
        public async Task<ActionResult> Index()
        {
            AuthenticationResult result = null;
            try
            {
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
                string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                string authority = String.Format(CultureInfo.InvariantCulture, Startup.aadInstance, tenantID, string.Empty);
                ClientCredential credential = new ClientCredential(Startup.clientId, Startup.clientSecret);
                
                // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
                AuthenticationContext authContext = new AuthenticationContext(authority, false, new NaiveSessionCache(userObjectID));                
                result = await authContext.AcquireTokenSilentAsync(new string[] { Startup.clientId }, credential, UserIdentifier.AnyUser);

                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, serviceUrl + "/api/todolist");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.Token);
                HttpResponseMessage response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    String responseString = await response.Content.ReadAsStringAsync();
                    JArray todoList = JArray.Parse(responseString);
                    ViewBag.TodoList = todoList;
                    return View();
                }
                else
                {
                    // If the call failed with access denied, then drop the current access token from the cache, 
                    // and show the user an error indicating they might need to sign-in again.
                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Scope.Contains(Startup.clientId));
                        foreach (TokenCacheItem tci in todoTokens)
                            authContext.TokenCache.DeleteItem(tci);

                        return new RedirectResult("/Error?message=Error: " + response.ReasonPhrase + " You might need to sign in again.");
                    }
                }

                return new RedirectResult("/Error?message=An Error Occurred Reading To Do List: " + response.StatusCode);
            }
            catch (AdalException ee)
            {
                // If ADAL could not get a token silently, show the user an error indicating they might need to sign in again.
                return new RedirectResult("/Error?message=An Error Occurred Reading To Do List: " + ee.Message + " You might need to log out and log back in.");
            }
            catch (Exception ex)
            {
                return new RedirectResult("/Error?message=An Error Occurred Reading To Do List: " + ex.Message);
            }
        }
Example #29
0
        public IEnumerable <TeamProjectReference> InteractiveADALExchangeGraphTokenForVSTSToken(string vstsAccountName, string applicationId)
        {
            AuthenticationContext authenticationContext = new AadAuthenticationContext("https://login.windows.net/common", validateAuthority: true);
            var authenticationResultTask = authenticationContext.AcquireTokenAsync(GraphResourceId, applicationId, new Uri(RedirectUri), new PlatformParameters(PromptBehavior.Auto));
            AuthenticationResult authenticationResult = authenticationResultTask.Result;

            authenticationResultTask = authenticationContext.AcquireTokenSilentAsync(VSTSResourceId, applicationId);
            authenticationResult     = authenticationResultTask.Result;

            VssOAuthAccessTokenCredential oAuthCredential = new VssOAuthAccessTokenCredential(authenticationResult.AccessToken);

            return(ListProjectsViaClientLibrary(vstsAccountName, oAuthCredential));
        }
    // GET: Calendar
    public async Task<ActionResult> Index() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      // discover contact endpoint
      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // create O365 discovery client 
      DiscoveryClient discovery = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);

          return authResult.AccessToken;
        });

      // query discovery service for endpoint for 'calendar' endpoint
      var dcr = await discovery.DiscoverCapabilityAsync("Calendar");

      // create Outlook client using the calendar api endpoint
      OutlookServicesClient client = new OutlookServicesClient(dcr.ServiceEndpointUri,
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, clientCredential,
          userIdentifier);

          return authResult.AccessToken;
        });

      // get contacts
      var results = await client.Me.Events.Take(20).ExecuteAsync();
      ViewBag.Events = results.CurrentPage.OrderBy(c => c.Start);

      return View();
    }
Example #31
0
        /// <summary>
        /// Get a Microsoft Graph access token from Azure AD V1.
        /// </summary>
        /// <returns>An oauth2 access token.</returns>
        internal static async Task <string> AuthenticateAdalUserAsync()
        {
            ADAL.AuthenticationResult authenticationResult = null;
            try
            {
                authenticationResult = await _azureAdContext.AcquireTokenSilentAsync(_resourceUri, _appClientId);
            }
            catch (Exception)
            {
                authenticationResult = await _azureAdContext.AcquireTokenAsync(_resourceUri, _appClientId, new Uri(DefaultRedirectUri), new ADAL.PlatformParameters(ADAL.PromptBehavior.RefreshSession, false));
            }

            return(authenticationResult.AccessToken);
        }
Example #32
0
        public static async Task<string> GetTokenForApplicationAsync(string signedInUserID, 
            string tenantID, string userObjectID, string resource)
        {
            // Get a token for the Graph without triggering any user 
            // interaction (from the cache, via multi-resource refresh token, etc.).
            ClientCredential clientcred = new ClientCredential(ClientId, AppKey);

            // Initialize AuthenticationContext with the token cache of 
            // the currently signed in user, as kept in the app's database.
            AuthenticationContext authenticationContext = new AuthenticationContext(AADInstance + tenantID,
                new ADALTokenCache(signedInUserID));
            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(resource,
                clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
            return authenticationResult.AccessToken;
        }
        public async Task AutoPromptBehaviorWithExpiredAccessTokenAndGoodRefreshTokenInCacheTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow)
                {
                    UserInfo =
                        new UserInfo()
                    {
                        DisplayableId = TestConstants.DefaultDisplayableId,
                        UniqueId      = TestConstants.DefaultUniqueId
                    }
                },
            },
                                                       TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                       new CallState(new Guid())).ConfigureAwait(false);

            ResetInstanceDiscovery();

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>()
                {
                    { "grant_type", "refresh_token" }
                }
            });

            AuthenticationResult result =
                await
                context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId),
                                                new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual("some-access-token", result.AccessToken);

            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
        internal static async Task<SharePointClient> EnsureSharePointClientCreatedAsync(string capabilityName)
        {

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // !!! NOTE: DO NOT USE NaiveSessionCache IN PRODUCTION. A MORE PERSISTENT CACHE SUCH AS A DATABASE IS RECOMMENDED FOR PRODUCTION USE !!!!
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new NaiveSessionCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId,
                                                                                   new ClientCredential(SettingsHelper.ClientId,
                                                                                                        SettingsHelper.AppKey),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));
                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);

                return new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                                                                                   new ClientCredential(SettingsHelper.ClientId,
                                                                                                        SettingsHelper.AppKey),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });
            }
            catch (AdalException exception)
            {
                //Partially handle token acquisition failure here and bubble it up to the controller
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
Example #35
0
		public static async Task<string> GetAccessToken()
		{
			var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
			var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

			AuthenticationContext authContext =
				new AuthenticationContext(SettingsHelper.Authority,
																		new ADALTokenCache(signInUserId));

			var authResult = await authContext.AcquireTokenSilentAsync(
							SettingsHelper.MSGraphResource,
							new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey),
							new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

			return authResult.AccessToken;

		}
    private async Task<string> GetAccessToken() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;


      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // authenticate
      var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.SharePointServiceResourceId, clientCredential, userIdentifier);

      // obtain access token
      return authResult.AccessToken;
    }
Example #37
0
 private static async Task <adal.AuthenticationResult> Authenticate(adal.AuthenticationContext context, string resource)
 {
     try
     {
         return(await context.AcquireTokenSilentAsync(resource, _clientId));
     }
     catch (adal.AdalException ex)
     {
         // There is no access token in the cache, so prompt the user to sign-in.
         if (ex.ErrorCode == adal.AdalError.UserInteractionRequired ||
             ex.ErrorCode == adal.AdalError.FailedToAcquireTokenSilently)
         {
             return(await context.AcquireTokenAsync(resource, _clientId, new Uri(_redirectUri),
                                                    new adal.PlatformParameters(adal.PromptBehavior.Auto)));
         }
         // Some other error.
         throw;
     }
 }
        private async Task <AuthenticationResult> AcquireTokenSilentAsyncInternal(string resourceUrl, string clientId,
                                                                                  UserIdentifier userIdentifier)
        {
            OriginalAuthenticationResult authResult = null;
            AuthenticationResult         result;

            try
            {
                authResult = await _context.AcquireTokenSilentAsync(resourceUrl, clientId, userIdentifier.GetOriginalUserIdentifier());

                result = AuthenticationResult.From(authResult);
            }
            catch (Exception ex)
            {
                result = new AuthenticationResult(ex);
            }

            return(result);
        }
Example #39
0
        public static async Task <AuthenticationResult> GetToken(OAuthContext oAuthContext)
        {
            // Get OAuth token using client credentials
            string tenantName = oAuthContext.tenantName;

            if (_authenticationContext == null)
            {
                _authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(oAuthContext.authUrl + "/" + tenantName, _tokenCache);
            }

            AuthenticationResult authenticationResult = null;

            if (oAuthContext.ObtainUserConsent)
            {
                // We need to get user consent

                FormGetUserPermission formGetPermission = new FormGetUserPermission(oAuthContext);
                if (formGetPermission.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string code = formGetPermission.Code;
                    // When we get our token, it will be cached in the TokenCache, so next time the silent calls will work
                    if (oAuthContext.cert == null)
                    {
                        ClientCredential clientCred = new ClientCredential(oAuthContext.clientId, oAuthContext.secretKey);
                        authenticationResult = await _authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(oAuthContext.redirectUrl), clientCred);
                    }
                    else
                    {
                        ClientAssertionCertificate clientCert = new ClientAssertionCertificate(oAuthContext.clientId, oAuthContext.cert);
                        authenticationResult = await _authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(oAuthContext.redirectUrl), clientCert);
                    }
                }
                return(authenticationResult);
            }

            if (oAuthContext.isNativeApplication)
            {
                if (oAuthContext.adminConsent)
                {
                    authenticationResult = await _authenticationContext.AcquireTokenAsync(oAuthContext.resource,
                                                                                          oAuthContext.clientId,
                                                                                          new Uri(oAuthContext.redirectUrl),
                                                                                          new PlatformParameters(PromptBehavior.Always),
                                                                                          UserIdentifier.AnyUser,
                                                                                          "prompt=admin_consent");
                }
                else
                {
                    authenticationResult = await _authenticationContext.AcquireTokenAsync(oAuthContext.resource, oAuthContext.clientId, new Uri(oAuthContext.redirectUrl), new PlatformParameters(PromptBehavior.Always));
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(oAuthContext.userId))
                {
                    // We have the UserId for the mailbox we want to access, so we'll try to get a token silently (we should have a cached token)
                    try
                    {
                        if (oAuthContext.cert == null)
                        {
                            ClientCredential clientCred = new ClientCredential(oAuthContext.clientId, oAuthContext.secretKey);
                            authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(oAuthContext.resource, clientCred, new UserIdentifier(oAuthContext.userId, UserIdentifierType.UniqueId));
                        }
                        else
                        {
                            ClientAssertionCertificate clientCert = new ClientAssertionCertificate(oAuthContext.clientId, oAuthContext.cert);
                            authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(oAuthContext.resource, clientCert, new UserIdentifier(oAuthContext.userId, UserIdentifierType.UniqueId));
                        }
                        return(authenticationResult);
                    }
                    catch (Exception ex)
                    {
                        _lastError = ex;
                    }
                }
            }
            return(authenticationResult);
        }