当前位置: 首页>>代码示例>>C#>>正文


C# AuthenticationContext.AcquireTokenSilentAsync方法代码示例

本文整理汇总了C#中Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenSilentAsync方法的典型用法代码示例。如果您正苦于以下问题:C# AuthenticationContext.AcquireTokenSilentAsync方法的具体用法?C# AuthenticationContext.AcquireTokenSilentAsync怎么用?C# AuthenticationContext.AcquireTokenSilentAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext的用法示例。


在下文中一共展示了AuthenticationContext.AcquireTokenSilentAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Index

        // 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);
        }
开发者ID:jontang168,项目名称:GPX-FileHandler,代码行数:61,代码来源:MyFilesController.cs

示例2: EnsureClientCreated

    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;
        });
    }
开发者ID:iambmelt,项目名称:TrainingContent,代码行数:32,代码来源:MyContactRepository.cs

示例3: InitOneNoteRestConnection

    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;
    }
开发者ID:modulexcite,项目名称:TrainingContent,代码行数:32,代码来源:NotebookRepository.cs

示例4: GetSharePointClient

        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;
        }
开发者ID:robledosm,项目名称:OneDriveForBusiness-Explorer-MVC,代码行数:26,代码来源:OneDriveExplorerController.cs

示例5: Index

        // 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);
        }
开发者ID:lalitm14,项目名称:office365Code,代码行数:59,代码来源:ContactsController.cs

示例6: Index

        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" });
            }
        }
开发者ID:jinujoseph,项目名称:NuGet.Services.Metadata,代码行数:58,代码来源:ValidateController.cs

示例7: EnsureSharePointClientCreatedAsync

        // 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;
            }
        }
开发者ID:se02035,项目名称:WEcanHELP,代码行数:63,代码来源:UserController.cs

示例8: Sites

        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);
        }
开发者ID:dougperkes,项目名称:O365-SharePoint-FilePush,代码行数:53,代码来源:HomeController.cs

示例9: EnsureSharePointClientCreatedAsync

        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;
            }
        }
开发者ID:OneBitSoftware,项目名称:AADGraphAPI,代码行数:50,代码来源:AuthenticationHelper.cs

示例10: GetTokenHelperAsync

        // 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;
            }
        }
开发者ID:OfficeDev,项目名称:O365-WinPhone-ArtCurator,代码行数:26,代码来源:AuthenticationHelper.cs

示例11: GetAccessToken

    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;
    }
开发者ID:chrissimusokwe,项目名称:TrainingContent,代码行数:27,代码来源:AadHelper.cs

示例12: Open

    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();
    }
开发者ID:chrissimusokwe,项目名称:TrainingContent,代码行数:33,代码来源:BlogHandlerController.cs

示例13: GetAccessToken

        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;
        }
开发者ID:CriticalPathTraining,项目名称:CBD365,代码行数:30,代码来源:TokenManager.cs

示例14: Index

    // 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);
    }
开发者ID:beauxjames,项目名称:pres-enterprise-ng-mstech,代码行数:27,代码来源:DiscoveryController.cs

示例15: GetTokenAsync

        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;
            }
        }
开发者ID:DeanBecker,项目名称:asp-net-mvc-csharp-salesprojectlog,代码行数:25,代码来源:OfficeIntegration.cs


注:本文中的Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenSilentAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。