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


C# AuthenticationContext.AcquireTokenByRefreshToken方法代码示例

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


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

示例1: RefreshToken

 public Tokens RefreshToken(Client client, Token refreshToken)
 {
     var tokenCache = new TokenCache();
     var authenticationContext = new AuthenticationContext(AuthorityUri, tokenCache);
     var result = authenticationContext.AcquireTokenByRefreshToken(refreshToken, client, ResourceUri);
     var tokens = new Tokens
     {
         AccessToken = result.AccessToken,
         RefreshToken = result.RefreshToken,
         ExpiresOn = result.ExpiresOn
     };
     return tokens;
 }
开发者ID:msdevno,项目名称:PowerBIDotNet,代码行数:13,代码来源:Authentication.cs

示例2: RefreshAccessToken

        public static void RefreshAccessToken(this ApiManagementClient apiManagementClient)
        {
            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                // if it's playback then do nothing
                return;
            }

            var testEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            var context = new AuthenticationContext(new Uri(testEnvironment.Endpoints.AADAuthUri, testEnvironment.Tenant).AbsoluteUri);

            var result = context.AcquireToken("https://management.core.windows.net/", testEnvironment.ClientId, new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior.Auto);
            var newToken = context.AcquireTokenByRefreshToken(result.RefreshToken, testEnvironment.ClientId, "https://management.core.windows.net/");

            ((TokenCloudCredentials) apiManagementClient.Credentials).Token = newToken.AccessToken;
        }
开发者ID:avkaur,项目名称:azure-sdk-for-net,代码行数:16,代码来源:ApiManagementHelper.cs

示例3: GetBearerToken

        public string GetBearerToken()
        {
            string resourceUri = "https://analysis.windows.net/powerbi/api";
            Claim userObjectIdClaim = ClaimsPrincipal.Current.FindFirst(Globals.ObjectIdClaimType);
            Claim tenantIdClaim = ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType);
            if (userObjectIdClaim != null && tenantIdClaim != null)
            {
                var authContext = new AuthenticationContext(
                    String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantIdClaim.Value),
                    new TokenDbCache(userObjectIdClaim.Value));
                var code = authContext.TokenCache.ReadItems().First().RefreshToken;
                var token = authContext.AcquireTokenByRefreshToken(code, new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey), resourceUri);

                return token.CreateAuthorizationHeader();
            }

            throw new UnauthorizedAccessException();
        }
开发者ID:elastacloud,项目名称:bisharp-samples,代码行数:18,代码来源:PowerBIController.cs

示例4: GetAccessTokenFromRefreshToken

 /// <summary>
 /// Try to get a new access token for this resource using a refresh token.
 /// If successful, this method will cache the access token for future use.
 /// If this fails, return null, signaling the caller to do the OAuth redirect.
 /// </summary>
 public static string GetAccessTokenFromRefreshToken(string resourceId)
 {
     // Redeem the refresh token for an access token:
     try
     {
         string refreshToken = Storage.OneDrive.RefreshToken;
         ClientCredential credential = new ClientCredential(AppConstants.OneDriveClientId, AppConstants.OneDriveClientSecret);
         string authority = string.Format(CultureInfo.InvariantCulture, OAuthUrl, "common");
         AuthenticationContext authContext = new AuthenticationContext(authority);
         AuthenticationResult result = authContext.AcquireTokenByRefreshToken(
             refreshToken, credential, resourceId);
         
         return result.AccessToken;
     }
     catch (Exception)//ActiveDirectoryAuthenticationException)
     {
         return null;
     }
 }
开发者ID:alex-bluemix,项目名称:Office-Apps-Attachment-Code-Samples,代码行数:24,代码来源:OneDriveController.cs

示例5: RefreshAccessToken

    public ActionResult RefreshAccessToken() {

      string refreshToken = CustomAuthenticationManager.GetRefreshToken();

      ClientCredential credential =
        new ClientCredential(DemoConstants.ClientId, DemoConstants.ClientSecret);

      string resource = DemoConstants.TargetResource;
   
      AuthenticationContext authenticationContext = 
        new AuthenticationContext(DemoConstants.urlAuthorizationEndpoint);

      AuthenticationResult authenticationResult =
        authenticationContext.AcquireTokenByRefreshToken(refreshToken, credential, resource);

      CustomAuthenticationManager.RefreshAccessToken(authenticationResult);

      return RedirectToAction("AccessToken", "TokenViewer");
    }
开发者ID:CriticalPathTraining,项目名称:DSU365,代码行数:19,代码来源:AccountController.cs

示例6: Authenticate

        public bool Authenticate()
        {
            _token = string.Empty;

            AuthenticationContext authContext = new AuthenticationContext(_authorityUri);
            if (!File.Exists("token.txt"))
            {
                AuthenticationResult ar = authContext.AcquireToken(_resourceUri, _clientId, new Uri(_redirectUri));
                _token = ar.AccessToken;
                File.WriteAllText("token.txt", ar.RefreshToken);
            }
            else
            {
                string refreshToken = File.ReadAllText("token.txt");
                AuthenticationResult ar = authContext.AcquireTokenByRefreshToken(refreshToken, _clientId);
                _token = ar.AccessToken;
            }

            return (!string.IsNullOrEmpty(_token));
        }
开发者ID:slunyakin,项目名称:RealTime-PowerBI,代码行数:20,代码来源:PowerBI.cs

示例7: GetAccessTokenFromRefreshToken

        public static string GetAccessTokenFromRefreshToken(string tenantId, string resourceId)
        {
            //
            // Try to get a new access token for this resource using a refresh token.
            // If this fails, return null signalling the caller to do the OAuth redirect.
            //
            AuthenticationResult result = null;
            string refreshToken = null;

            //
            // Fetch the refresh token from the cache
            //
            refreshToken = (string)GetRefreshTokenFromCache();
            if (refreshToken == null)
            {
                //
                // No refresh token - the caller will need to send the user to get an auth code.  Return null.
                //
                return null;
            }

            try
            {
                //
                // Redeem the refresh token for an access token
                //
                ClientCredential clientcred = new ClientCredential(clientId, appKey);
                string authority = string.Format(aadInstance, tenantId);
                AuthenticationContext authcontext = new AuthenticationContext(authority);
                result = authcontext.AcquireTokenByRefreshToken(refreshToken, clientcred, resourceId);

                //
                // Save the authorization header for this resource and the refresh token in separate cookies
                //
                SaveAccessTokenInCache(resourceId, result.AccessToken, (result.ExpiresOn.AddMinutes(-5)).ToString());
                SaveRefreshTokenInCache(result.RefreshToken);

                return result.AccessToken;
            }
            catch 
            {
                //
                // If the refresh token is also expired, remove it from the cache, and send the user off to do a new OAuth auth code request
                //
                RemoveRefreshTokenFromCache();

                return null;
            }

        }
开发者ID:developerlucky,项目名称:DevCampTraining,代码行数:50,代码来源:OAuthController.cs

示例8: GetAccessTokenFromRefreshToken

        /// <summary>
        /// Try to get a new access token for this resource using a refresh token.
        /// If successful, this method will cache the access token for future use.
        /// If this fails, return null, signaling the caller to do the OAuth redirect.
        /// </summary>
        private static string GetAccessTokenFromRefreshToken(string resourceId)
        {
            string refreshToken = Office365Cache.GetRefreshToken().Value;
            if (refreshToken == null)
            {
                // If no refresh token, the caller will need to send the user to do an OAuth redirect.
                return null;
            }

            // Redeem the refresh token for an access token:
            try
            {
                ClientCredential credential = new ClientCredential(AppPrincipalId, AppKey);
                string authority = string.Format(CultureInfo.InvariantCulture, OAuthUrl, "common");
                AuthenticationContext authContext = new AuthenticationContext(authority);
                AuthenticationResult result = authContext.AcquireTokenByRefreshToken(
                    refreshToken, AppPrincipalId, credential, resourceId);

                // Cache the access token and update the refresh token:
                Office365Cache.GetAccessToken(resourceId).Value = result.AccessToken;
                Office365Cache.GetRefreshToken().Value = result.RefreshToken;

                return result.AccessToken;
            }
            catch (ActiveDirectoryAuthenticationException)
            {
                // Forget the refresh token and return null, so as to start the OAuth redirect from scratch.
                Office365Cache.GetRefreshToken().RemoveFromCache();
                return null;
            }
        }
开发者ID:CedarLogic,项目名称:CustomOffice365OWA,代码行数:36,代码来源:Office365CommonController.cs

示例9: Index

        // GET: UserProfile
        public ActionResult Index()
        {
            string clientId = ConfigurationManager.AppSettings["ida:ClientID"];
            string appKey = ConfigurationManager.AppSettings["ida:Password"];
            string graphResourceID = "https://graph.windows.net";
            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;

            bool validTokenPresent = true;
            TodoListWebApp.Models.TokenCacheEntry tce = null;
            //get a token using the cached values
            var existing = db.TokenCache.FirstOrDefault(a => (a.SignedInUser==signedInUserID) && (a.ResourceID == graphResourceID));
            if(existing!=null) //we have a token cache entry
            {
                tce = existing;
                //if the access token is expired
                if ( tce.Expiration.DateTime  < DateTime.Now)
                {
                    //use the refresh token to get a fresh set of tokens
                    try
                    {
                        ClientCredential clientcred = new ClientCredential(clientId, appKey);
                        AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID));
                        AuthenticationResult result = authContext.AcquireTokenByRefreshToken(tce.RefreshToken, clientId, clientcred, graphResourceID);
                        TodoListWebApp.Models.TokenCacheEntry tce2 = new TodoListWebApp.Models.TokenCacheEntry
                        {
                            SignedInUser = signedInUserID,
                            TokenRequestorUser = result.UserInfo.UserId,
                            ResourceID = graphResourceID,
                            AccessToken = result.AccessToken,
                            RefreshToken = result.RefreshToken,
                            Expiration = result.ExpiresOn.AddMinutes(-5)
                        };
                        db.TokenCache.Remove(tce);
                        db.TokenCache.Add(tce2);
                        db.SaveChanges();
                        tce = tce2;
                    }
                    catch
                    {
                        // the refresh token might be expired
                        tce = null;
                    }
                }
            } else // we don't have a cached token
            {
                tce = null;// it's already null, but for good measure...
            }

            if (tce != null)
            {
               // CallContext currentCallContext = new CallContext { AccessToken = tce.AccessToken, ClientRequestId = Guid.NewGuid(), TenantId = tenantID, ApiVersion = "2013-11-08" };

                 CallContext currentCallContext = new CallContext(tce.AccessToken, Guid.NewGuid(), "2013-11-08");

                GraphConnection graphConnection = new GraphConnection(currentCallContext);
                User user = graphConnection.Get<User>(userObjectID);
                return View(user);
            }
            else
            {
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return View();
            }
        }
开发者ID:kiwidev,项目名称:WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet,代码行数:67,代码来源:UserProfileController.cs

示例10: ConfigureAuth

        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {

                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        //
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        //

                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;

                            if ( certName.Length != 0)
                            {
                                // Create a Client Credential Using a Certificate
                                //
                                // Initialize the Certificate Credential to be used by ADAL.
                                // First find the matching certificate in the cert store.
                                //

                                X509Certificate2 cert = null;
                                X509Store store = new X509Store(StoreLocation.CurrentUser);
                                try
                                {
                                    store.Open(OpenFlags.ReadOnly);
                                    // Place all certificates in an X509Certificate2Collection object.
                                    X509Certificate2Collection certCollection = store.Certificates;
                                    // Find unexpired certificates.
                                    X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                                    // From the collection of unexpired certificates, find the ones with the correct name.
                                    X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false);
                                    if (signingCert.Count == 0)
                                    {
                                        // No matching certificate found.
                                        return Task.FromResult(0);
                                    }
                                    // Return the first certificate in the collection, has the right name and is current.
                                    cert = signingCert[0];
                                }
                                finally
                                {
                                    store.Close();
                                }

                                // Then create the certificate credential.
                                ClientAssertionCertificate credential = new ClientAssertionCertificate(clientId, cert);

                                string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
                                    "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                                AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                    code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                                AuthenticationHelper.token = result.AccessToken;
                            }
                            else
                            {
                                // Create a Client Credential Using an Application Key
                                ClientCredential credential = new ClientCredential(clientId, appKey);
                                string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
                                    "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                                AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                                Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                    code, uri, credential, graphResourceId);

                                result = authContext.AcquireTokenByRefreshToken(result.RefreshToken, credential);
                                AuthenticationHelper.token = result.AccessToken;
                            }

                            return Task.FromResult(0);
                        }

                    }

                });
        }
开发者ID:xzluo,项目名称:skypesalesforce,代码行数:88,代码来源:Startup.Auth.cs

示例11: Main


//.........这里部分代码省略.........

            // get members of a Group
            Uri membersUri = Utils.GetRequestUri<Group>(graphConnection, retrievedGroup.ObjectId, "members");

            BatchRequestItem secondItem = new BatchRequestItem(
                                        "GET",
                                        false,
                                        new Uri(membersUri.ToString()),
                                        null,
                                        String.Empty);

            // update an existing group's Description property

            retrievedGroup.Description = "New Employees in Washington State";

            BatchRequestItem thirdItem = new BatchRequestItem(
                                           "Patch",
                                            true,
                                            Utils.GetRequestUri<Group>(graphConnection,retrievedGroup.ObjectId),
                                            null,
                                            retrievedGroup.ToJson(true));

            // Execute the batch requst
            IList<BatchRequestItem> batchRequest = new BatchRequestItem[] { firstItem, secondItem, thirdItem };
            IList<BatchResponseItem> batchResponses = graphConnection.ExecuteBatch(batchRequest);

            int responseCount = 0;
            foreach (BatchResponseItem responseItem in batchResponses)
            {
                if (responseItem.Failed)
                {
                    Console.WriteLine("Failed: {0} {1}",
                                    responseItem.Exception.Code,
                                    responseItem.Exception.ErrorMessage);
                }
                else
                {
                    Console.WriteLine("Batch Item Result {0} succeeded {1}",
                                     responseCount++,
                                     !responseItem.Failed);
                }
            }

            // this next section shows how to access the signed-in user's mailbox.
            // First we get a new token for Office365 Exchange Online Resource
            // using the multi-resource refresh token tha was included when the previoius
            // token was acquired.
            // We can now request a new token for Office365 Exchange Online.
            //
            string office365Emailresource = "https://outlook.office365.com/";
            string office365Token = null;
            if (userAuthnResult.IsMultipleResourceRefreshToken)
            {
                userAuthnResult = authenticationContext.AcquireTokenByRefreshToken(userAuthnResult.RefreshToken, clientIdForUserAuthn, office365Emailresource);
                office365Token = userAuthnResult.AccessToken;

                //
                // Call the Office365 API and retrieve the top item from the user's mailbox.
                //
                string requestUrl = "https://outlook.office365.com/EWS/OData/Me/Inbox/Messages?$top=1";
                WebRequest getMailboxRequest;
                getMailboxRequest = WebRequest.Create(requestUrl);
                getMailboxRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + office365Token);
                Console.WriteLine("\n Getting the User's Mailbox Contents \n");

                //
                // Read the contents of the user's mailbox, and display to the console.
                //
                Stream objStream = null;
                try
                {
                    objStream = getMailboxRequest.GetResponse().GetResponseStream();
                    StreamReader objReader = new StreamReader(objStream);

                    string sLine = "";
                    int i = 0;

                    while (sLine != null)
                    {
                        i++;
                        sLine = objReader.ReadLine();
                        if (sLine != null)
                        {
                            Console.WriteLine("{0}:{1}", i, sLine);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\n Error Getting User's Mailbox: {0} \n", ex.Message);
                }
            }

            //*********************************************************************************************
            // End of Demo Console App
            //*********************************************************************************************
            Console.WriteLine("\nCompleted at {0} \n ClientRequestId: {1}", CurrentDateTime, ClientRequestId);
            Console.ReadKey();
            return;
        }
开发者ID:k-daimaruya,项目名称:ConsoleApp-GraphAPI-DotNet,代码行数:101,代码来源:Program.cs

示例12: RefreshAccessToken

        public string RefreshAccessToken(FormCollection form)
        {
            string spWebUrl = form["spWebUrl"];
            string tenantId = form["tenantId"];

            string refreshTokenContent = _refreshTokenManager.RetrieveToken(HttpContext.Request);

            var credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientKey);
            var authContext = new AuthenticationContext(SettingsHelper.AUTHORITY + tenantId);

            try
            {
                AuthenticationResult result = authContext.AcquireTokenByRefreshToken(refreshTokenContent, credential, spWebUrl);

                if (result == null)
                    throw new Exception("Error acquiring SharePoint AccessToken.");

                return result.AccessToken;
            }
            catch (AdalServiceException exception)
            {
                throw new Exception("SharePoint RefreshToken is invalid.", exception);
            }
        }
开发者ID:cheekyeagle,项目名称:Word-Add-in-ClauseLibrary-Code-Sample,代码行数:24,代码来源:AuthenticationController.cs


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