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


C# AuthenticationContext.AcquireTokenByRefreshTokenAsync方法代码示例

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


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

示例1: GetAccessToken

 private async Task<AuthenticationResult> GetAccessToken()
 {
     AuthenticationContext context = new AuthenticationContext(SettingsHelper.AzureADAuthority);
     var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
     AuthenticationResult result = (AuthenticationResult)this.Session[SettingsHelper.UserTokenCacheKey];
     return await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientCredential, SettingsHelper.UnifiedApiResource);
 }
开发者ID:martinkearn,项目名称:DontPanic,代码行数:7,代码来源:UserController.cs

示例2: Delete

        public async Task<ActionResult> Delete(Guid id)
        {
            //check for tenantId and refresh token in session
            if (Session["TenantID"] == null || Session["RefreshToken"] == null)
                return RedirectToAction("Error", "Home", new { error = "Session expired" });
            var tenantId = Session["TenantID"].ToString();
            var refreshToken = Session["RefreshToken"].ToString();

            //use authentication context to get access token to azure graph
            AuthenticationContext context = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId));
            var result = await context.AcquireTokenByRefreshTokenAsync(refreshToken, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), SettingsHelper.AADGraphResourceId);

            ////delete the app in Azure
            //HttpClient client = new HttpClient();
            //client.DefaultRequestHeaders.Add("Authorization", "Bearer " + result.AccessToken);
            //client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");
            //using (HttpResponseMessage response = await client.DeleteAsync(new Uri(string.Format("https://graph.windows.net/{0}/applications?$filter=appId eq '{1}'&api-version=1.5", tenantId, id.ToString()), UriKind.Absolute)))
            //{
            //    if (response.IsSuccessStatusCode)
            //    {
            //        //delete the app in the database
            //    }
            //}

            //delete the app in the database
            using (ApplicationEntities entities = new ApplicationEntities())
            {
                var item = entities.Applications.FirstOrDefault(i => i.Id == id);
                entities.Applications.Remove(item);
                entities.SaveChanges();
            }

            return Redirect("/Application");
        }
开发者ID:richdizz,项目名称:AzureAD-EasyAuth,代码行数:34,代码来源:ApplicationController.cs

示例3: GetAccessTokenFromRefreshToken

 public static async Task<AuthenticationResult> GetAccessTokenFromRefreshToken(string refreshToken)
 {
     try
     {
         var authContext = new AuthenticationContext("https://login.windows.net/common", new ADALTokenCache(String.Empty));
         var clientCredential = new ClientCredential(DashConfiguration.ClientId, DashConfiguration.AppKey);
         return await authContext.AcquireTokenByRefreshTokenAsync(refreshToken, clientCredential);
     }
     catch (Exception ex)
     {
         DashTrace.TraceWarning("Error attempting to retrieve access token from refresh token. Details: {0}", ex);
     }
     return null;
 }
开发者ID:farukc,项目名称:Dash,代码行数:14,代码来源:DelegationToken.cs

示例4: CheckToken

        internal async Task CheckToken()
        {
            if (PowerBIController.authorization == null)
                PowerBIController.authorization = await ReadTokenFromStorage();

            if (PowerBIController.authorization == null)
                return;

            if (DateTime.UtcNow.CompareTo(PowerBIController.authorization.Expires) >= 0)
            {
                AuthenticationContext AC = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
                ClientCredential cc = new ClientCredential(clientId, clientSecret);
                var ADALResult = await AC.AcquireTokenByRefreshTokenAsync(PowerBIController.authorization.RefreshToken, cc);
                PowerBIController.authorization = new AuthResult { Expires = ADALResult.ExpiresOn.UtcDateTime, AccessToken = ADALResult.AccessToken, RefreshToken = ADALResult.RefreshToken };
                await WriteTokenToStorage(PowerBIController.authorization);
            }
        }
开发者ID:jeffhollan,项目名称:PowerBIAPI,代码行数:17,代码来源:AuthenticationController.cs

示例5: LoginAsync

        public override async Task<string> LoginAsync(bool clearCache, string authorityId, string redirectUri, string resourceId, string clientId)
        {
            var context = new AuthenticationContext(authorityId);
            var result = await context.AcquireTokenAsync(resourceId, clientId);

            // Build our token
            var token = JObject.FromObject(new
            {
                access_token = result.AccessToken,
            });

            // Request access to Azure Mobile Services
            await MobileServiceClientProvider.MobileClient.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, token);

            var authContext = new AuthenticationContext(ConfigurationHub.ReadConfigurationValue("AadAuthority"), false);

            // Get the sharepoint token
            var authenticationResult = await authContext.AcquireTokenByRefreshTokenAsync(result.RefreshToken, ConfigurationHub.ReadConfigurationValue("AadClientID"), ConfigurationHub.ReadConfigurationValue("SharePointResource"));
            State.SharePointToken = authenticationResult.AccessToken;

            return result.AccessToken;
        }
开发者ID:kirpasingh,项目名称:MicrosoftAzureTrainingKit,代码行数:22,代码来源:FacilityService.cs

示例6: AcquireTokenByRefreshTokenAsync

        /// <summary>
        /// Acquires an access token from the authority using a previously acquired refresh token.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="refreshToken">The <see cref="Token"/> of type <see cref="TokenType.Refresh"/>
        /// to be used to acquire the access token.</param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public async Task<TokenPair> AcquireTokenByRefreshTokenAsync(Uri targetUri, string clientId, string resource, Token refreshToken)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");
            Debug.Assert(refreshToken != null, "The refreshToken parameter is null");
            Debug.Assert(refreshToken.Type == TokenType.Refresh, "The value of refreshToken parameter is not a refresh token");
            Debug.Assert(!String.IsNullOrWhiteSpace(refreshToken.Value), "The value of refreshToken parameter is null or empty");

            TokenPair tokens = null;

            try
            {
                string authorityHostUrl = AuthorityHostUrl;

                if (refreshToken.TargetIdentity != Guid.Empty)
                {
                    authorityHostUrl = GetAuthorityUrl(refreshToken.TargetIdentity);

                    Trace.WriteLine("   authority host url set by refresh token.");
                }

                Trace.WriteLine(String.Format("   authority host url = '{0}'.", authorityHostUrl));

                AuthenticationContext authCtx = new AuthenticationContext(authorityHostUrl, _adalTokenCache);
                AuthenticationResult authResult = await authCtx.AcquireTokenByRefreshTokenAsync(refreshToken.Value, clientId, resource);
                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return tokens;
        }
开发者ID:dongruiqing,项目名称:Git-Credential-Manager-for-Windows,代码行数:50,代码来源:AzureAuthority.cs

示例7: ExecuteAsync


//.........这里部分代码省略.........
                    case CommandType.AquireTokenAsyncRCRePUX:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, arg.RedirectUri, 
                            (arg.PromptBehavior == PromptBehaviorProxy.Always) ? PromptBehavior.Always :
                            (arg.PromptBehavior == PromptBehaviorProxy.Never) ? PromptBehavior.Never : PromptBehavior.Auto,
                            (arg.UserName != null) ? new UserIdentifier(arg.UserName, UserIdentifierType.OptionalDisplayableId) : UserIdentifier.AnyUser, arg.Extra);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCReP:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, arg.RedirectUri, 
                            (arg.PromptBehavior == PromptBehaviorProxy.Always) ? PromptBehavior.Always :
                            (arg.PromptBehavior == PromptBehaviorProxy.Never) ? PromptBehavior.Never : PromptBehavior.Auto);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCRePU:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, arg.RedirectUri,                            
                            (arg.PromptBehavior == PromptBehaviorProxy.Always) ? PromptBehavior.Always :
                            (arg.PromptBehavior == PromptBehaviorProxy.Never) ? PromptBehavior.Never : PromptBehavior.Auto,
                            (arg.UserName != null) ? new UserIdentifier(arg.UserName, UserIdentifierType.OptionalDisplayableId) : UserIdentifier.AnyUser);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCP:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, 
                            (arg.PromptBehavior == PromptBehaviorProxy.Always) ? PromptBehavior.Always :
                            (arg.PromptBehavior == PromptBehaviorProxy.Never) ? PromptBehavior.Never : PromptBehavior.Auto);
                        break;
                    }

                    case CommandType.AcquireTokenByRefreshTokenAsyncRC:
                    {
                        result = await context.AcquireTokenByRefreshTokenAsync(arg.RefreshToken, arg.ClientId);
                        break;
                    }

                    case CommandType.AcquireTokenByRefreshTokenAsyncRCRe:
                    {
                        result = await context.AcquireTokenByRefreshTokenAsync(arg.RefreshToken, arg.ClientId, arg.Resource);
                        break;
                    }

                    case CommandType.CreateFromResourceUrlAsync:
                    {
                        var parameters = await AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(arg.Extra));
                        resultProxy = new AuthenticationResultProxy
                                 {
                                     AuthenticationParametersAuthority = parameters.Authority,
                                     AuthenticationParametersResource = parameters.Resource
                                 };
                        break;
                    }

                    case CommandType.CreateFromResponseAuthenticateHeader:
                    {
                        var parameters = AuthenticationParameters.CreateFromResponseAuthenticateHeader(arg.Extra);
                        resultProxy = new AuthenticationResultProxy
                        {
                            AuthenticationParametersAuthority = parameters.Authority,
                            AuthenticationParametersResource = parameters.Resource
                        };
                        break;
                    }

                    /*case CommandType.AcquireTokenByRefreshTokenAsyncRCC:
                    {
                        result = await context.AcquireTokenByRefreshTokenAsync(arg.RefreshToken, arg.ClientId,
                            (arg.ClientId != null && arg.ClientSecret != null) ? new ClientCredential(arg.ClientId, arg.ClientSecret) : null);
                        break;
                    }*/

                    default:
                        throw new Exception("Unknown command");
                }
            }

            return resultProxy ?? 
                       new AuthenticationResultProxy
                       {
                           AccessToken = result.AccessToken,
                           AccessTokenType = result.AccessTokenType,
                           ExpiresOn = result.ExpiresOn,
                           IsMultipleResourceRefreshToken =
                               result.IsMultipleResourceRefreshToken,
                           RefreshToken = result.RefreshToken,
                           IdToken = result.IdToken,
                           TenantId = result.TenantId,
                           UserInfo = result.UserInfo,
                           Error = result.Error,
                           ErrorDescription = result.ErrorDescription,
                           Status =
                               (result.Status == AuthenticationStatus.Success)
                                   ? AuthenticationStatusProxy.Success
                                   : ((result.Status == AuthenticationStatus.ClientError) ? AuthenticationStatusProxy.ClientError : AuthenticationStatusProxy.ServiceError)
                       };
        }
开发者ID:jpda,项目名称:azure-activedirectory-library-for-dotnet,代码行数:101,代码来源:CommandExecuter.cs

示例8: GetAuthorizationResultByRefreshToken

        protected async Task<TokenCacheInfo> GetAuthorizationResultByRefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo)
        {
            var azureEnvironment = this.AzureEnvironments;
            var authority = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], cacheInfo.TenantId);
            var context = new AuthenticationContext(
                authority: authority,
                validateAuthority: true,
                tokenCache: tokenCache);

            AuthenticationResult result = await context.AcquireTokenByRefreshTokenAsync(
                    refreshToken: cacheInfo.RefreshToken,
                    clientId: Constants.AADClientId,
                    resource: cacheInfo.Resource);

            var ret = new TokenCacheInfo(cacheInfo.Resource, result);
            ret.TenantId = cacheInfo.TenantId;
            ret.DisplayableId = cacheInfo.DisplayableId;
            tokenCache.Add(ret);
            return ret;
        }
开发者ID:v-gaw,项目名称:ARMClient,代码行数:20,代码来源:BaseAuthHelper.cs

示例9: Update

        public async Task<ActionResult> Update(Guid id)
        {
            //check for tenantId and refresh token in session
            if (Session["TenantID"] == null || Session["RefreshToken"] == null)
                return RedirectToAction("Error", "Home", new { error = "Session expired" });
            var tenantId = Session["TenantID"].ToString();
            var refreshToken = Session["RefreshToken"].ToString();

            //use authentication context to get access token to azure graph
            AuthenticationContext context = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId));
            var result = await context.AcquireTokenByRefreshTokenAsync(refreshToken, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), SettingsHelper.AADGraphResourceId);

            //get the registered app
            using (ApplicationEntities entities = new ApplicationEntities())
            {
                var tenantIdGuid = new Guid(tenantId);
                var dbApp = entities.Applications.FirstOrDefault(i => i.TenantId == tenantIdGuid && i.Id == id);
                var app = new ApplicationModel()
                {
                    CliendId = dbApp.Id,
                    Name = dbApp.Name,
                    AppOriginsFlat = dbApp.Origins,
                };
                app.AppOrigins = app.AppOriginsFlat.Split(';').ToList();

                //get the application from Azure AD to validate settings
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + result.AccessToken);
                client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");
                using (HttpResponseMessage response = await client.GetAsync(new Uri(string.Format("https://graph.windows.net/{0}/applications?$filter=appId eq '{1}'&api-version=1.5", tenantId, id.ToString()), UriKind.Absolute)))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        JObject oResponse = JObject.Parse(json);
                        var item = oResponse.SelectToken("d.results").ToObject<List<JsonApplication>>().FirstOrDefault();
                        app.SignOnURL = item.homepage;

                        //flatten the actual scopes
                        List<string> scopeIds = new List<string>();
                        foreach (var resource in item.requiredResourceAccess.results)
                        {
                            foreach (var scope in resource.resourceAccess.results)
                                scopeIds.Add(scope.id);
                        }

                        //update scopes based on what is selected
                        app.Permissions = PermissionModel.GetAllPermissions();
                        foreach (var perm in app.Permissions)
                        {
                            perm.Selected = scopeIds.Contains(perm.ScopeId.ToString());
                        }
                    }
                }

                return View(app);
            }
        }
开发者ID:richdizz,项目名称:AzureAD-EasyAuth,代码行数:58,代码来源:ApplicationController.cs

示例10: Add

        public async Task<ActionResult> Add(ApplicationModel application)
        {
            //check for tenantId and refresh token in session
            if (Session["TenantID"] == null || Session["RefreshToken"] == null)
                return RedirectToAction("Error", "Home", new { error = "Session expired" });
            var tenantId = Session["TenantID"].ToString();
            var refreshToken = Session["RefreshToken"].ToString();

            //use authentication context to get access token to azure graph
            AuthenticationContext context = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId));
            var result = await context.AcquireTokenByRefreshTokenAsync(refreshToken, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), SettingsHelper.AADGraphResourceId);

            //determine which scopes are selected
            List<Scopes> scopes = new List<Scopes>();
            foreach (var scope in AppScopes.ScopeIds.Keys)
            {
                if (Request[AppScopes.ScopeIds[scope]] != null)
                {
                    scopes.Add(scope);
                }
            }

            //get the domain
            var upn = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn").Value;
            upn = upn.Substring(upn.IndexOf('@') + 1);
            upn = upn.Substring(0, upn.IndexOf('.'));

            //create the application registration
            var appResult = AppRegistration.CreateWebAppRegistration(result.AccessToken, tenantId, application.Name, Request["hdnSignOnUrlPrefix"] + application.SignOnURL,
                String.Format("https://{0}.onmicrosoft.com/{1}", upn, application.Name.Replace(" ", "")), "https://easyauth.azurewebsites.net/OAuth/AuthCode", true, true, scopes);

            //Add to database
            using (ApplicationEntities entities = new ApplicationEntities())
            {
                Application app = new Application()
                {
                    Id = new Guid(appResult["client_id"]),
                    Secret = appResult["client_secret"],
                    Origins = Request["AppOriginsFlat"],
                    Name = application.Name,
                    TenantId = new Guid(tenantId)
                };
                entities.Applications.Add(app);
                entities.SaveChanges();
            }

            return Redirect("/Application");
        }
开发者ID:richdizz,项目名称:AzureAD-EasyAuth,代码行数:48,代码来源:ApplicationController.cs

示例11: GetAccessToken

 private async Task<AuthenticationResult> GetAccessToken(string resource, string refresh)
 {
     AuthenticationContext context = new AuthenticationContext(SettingsHelper.AzureADAuthority);
     var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
     return await context.AcquireTokenByRefreshTokenAsync(refresh, clientCredential, resource);
 }
开发者ID:modulexcite,项目名称:Image-FileHandler,代码行数:6,代码来源:SaveController.cs


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