コード例 #1
0
        /// <summary>
        /// Authenticate an user and navigate to mainpage if success.
        /// </summary>
        public async void AuthenticateUser()
        {
#if WINDOWS_APP
            var authenticationContext = new AuthenticationContext(AppSettings.AuthenticationUri);

            AuthenticationResult authResult = await authenticationContext.AcquireTokenAsync(
                AppSettings.ApiUri.ToString(),
                AppSettings.ClientId,
                new Uri(AppSettings.ReplyUri),
                PromptBehavior.Always,
                string.Empty);

            if (authResult.ExpiresOn < DateTime.UtcNow)
            {
                authResult = await authenticationContext.AcquireTokenByRefreshTokenAsync(authResult.RefreshToken, AppSettings.ClientId);
            }


            if (authResult.Status == AuthenticationStatus.Succeeded)
            {
                myCompanyClient.RefreshToken(authResult.AccessToken);
                AppSettings.SecurityToken = String.Format("Bearer {0}", authResult.AccessToken);
                AppSettings.SecurityTokenExpirationDateTime = authResult.ExpiresOn;
                this.navService.NavigateToMainPage();
            }
#endif
        }
コード例 #2
0
 private async Task<AuthenticationResult> GetAccessToken(string resource)
 {
     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, resource);
 }
コード例 #3
0
        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));
        }
コード例 #4
0
        public override async Task <AuthenticationResult> AcquireTokenByRefreshToken(string resource)
        {
            await InitializeAuthentication();

            var authResult = await authContext.AcquireTokenByRefreshTokenAsync(this.Result.RefreshToken, this.ClientId, resource);

            return(Convert(authResult));
        }
コード例 #5
0
        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.AcquireTokenAsync(SettingsHelper.UnifiedApiResource, clientCredential);
            //return await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientCredential, SettingsHelper.UnifiedApiResource);
            return(await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientCredential, "https://api.office.com/discovery/"));
        }
コード例 #6
0
ファイル: UserController.cs プロジェクト: amarinhub/GraphMvc
        private async Task <AuthenticationResult> GetAccessToken()
        {
            AuthenticationContext context = new AuthenticationContext(SettingsHelper.AzureADAuthority);
            var clientCredential          = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

            // get the Session[User_Token] saved from 'Startup.Auth.cs'
            AuthenticationResult result = (AuthenticationResult)this.Session[SettingsHelper.UserTokenCacheKey];

            return(await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientCredential, SettingsHelper.UnifiedApiResource));
        }
コード例 #7
0
        public async Task <string> GetTokenForSecondResource(string authority, AuthenticationResult authResult1)
        {
            AuthenticationContext authContext = new AuthenticationContext(authority, new FileCache());

            var resourceId2 = "https://enterprisedirectory.onmicrosoft.com/0e-d2dbcdb54f6e";
            var result      = await authContext.AcquireTokenByRefreshTokenAsync(authResult1.RefreshToken, this.authSettings.ClientId, resourceId2);

            //OfflineTokenValue(authContext);
            return(result.AccessToken);
        }
コード例 #8
0
        public static async Task <string> GetAccessTokenFromRefreshTokenAsync(string refreshToken)
        {
            string authority = string.Format(System.Globalization.CultureInfo.InvariantCulture, aadInstance, "common");

            AuthenticationContext authContext = new AuthenticationContext(authority, false);
            AuthenticationResult  authResult  = await authContext.AcquireTokenByRefreshTokenAsync(
                refreshToken,
                credential,
                resourceId);

            return(authResult.AccessToken);
        }
コード例 #9
0
        public static void RefreshToken(SharePointCrawlJobData sharePointCrawlJobData)
        {
            string apiVersion = "9.1";
            string webApiUrl  = $"{sharePointCrawlJobData.Url}/api/data/v{apiVersion}/";

            var userCredential = new UserCredential(sharePointCrawlJobData.UserName, sharePointCrawlJobData.Password);
            var authParameters = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(webApiUrl)).Result;
            var authContext    = new AuthenticationContext(authParameters.Authority, false);
            var authResult     = authContext.AcquireTokenAsync(authParameters.Resource, sharePointCrawlJobData.ClientId, userCredential).Result;
            var refreshToken   = authContext.AcquireTokenByRefreshTokenAsync(authResult.RefreshToken, sharePointCrawlJobData.ClientId).Result;

            sharePointCrawlJobData.ApiKey = refreshToken.AccessToken;
        }
コード例 #10
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (_authResult == null)
            {
                var authParams = await AuthenticationParameters.CreateFromResourceUrlAsync(_resourceUri);

                _authContext = new AuthenticationContext(authParams.Authority);
                _authResult  = _authContext.AcquireToken(authParams.Resource, _clientId, _credential);
            }

            if (_authResult.ExpiresOn < DateTimeOffset.UtcNow)
            {
                _authResult = await _authContext.AcquireTokenByRefreshTokenAsync(_authResult.RefreshToken, _clientId);
            }

            request.Headers.Authorization = new AuthenticationHeaderValue(_authResult.AccessTokenType, _authResult.AccessToken);

            return(await base.SendAsync(request, cancellationToken));
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: asix7/AuthAzureAD
        static void Main(string[] args)
        {
            string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            AuthenticationContext authContext = new AuthenticationContext(authority);

            UserCredential uc = new UserCredential("*****@*****.**", "Hqtumc2017");

            var result = GetAccessToken(authContext, todoListResourceId, clientId, uc, authority);
            var token  = result.AccessToken;


            Console.WriteLine(token);

            token = authContext.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientId).Result.AccessToken;

            Console.WriteLine(token);
            Console.Read();
        }
コード例 #12
0
        protected async Task <TokenCacheInfo> GetAuthorizationResultByRefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo)
        {
            var authority = String.Format("{0}/{1}", ARMConfiguration.AADLoginUrl, cacheInfo.TenantId);
            var context   = new AuthenticationContext(
                authority: authority,
                validateAuthority: true,
                tokenCache: tokenCache);

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

            var ret = new TokenCacheInfo(cacheInfo.Resource, result);

            ret.TenantId      = cacheInfo.TenantId;
            ret.DisplayableId = cacheInfo.DisplayableId;
            ret.ClientId      = cacheInfo.ClientId;
            tokenCache.Add(ret);
            return(ret);
        }
コード例 #13
0
ファイル: BaseAuthHelper.cs プロジェクト: zangdalei/ARMClient
        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);
        }
コード例 #14
0
        /// <summary>
        /// Gets an Azure access token that can be used to call into the Azure ARM apis.
        /// </summary>
        /// <returns>A user token to access Azure ARM</returns>
        static async Task <string> GetAzureAccessTokenAsync()
        {
            if (!string.IsNullOrWhiteSpace(azureToken))
            {
                return(azureToken);
            }

            var commonToken = GetCommonAzureAccessToken();
            var tenantId    = (await GetTenantIdsAsync(commonToken.AccessToken)).FirstOrDefault();

            if (string.IsNullOrWhiteSpace(tenantId))
            {
                throw new InvalidOperationException("Unable to get tenant id for user accout");
            }

            var authority   = string.Format("https://login.windows.net/{0}/oauth2/authorize", tenantId);
            var authContext = new AuthenticationContext(authority);
            var result      = await authContext.AcquireTokenByRefreshTokenAsync(commonToken.RefreshToken, clientId, armResource);

            return(azureToken = result.AccessToken);
        }
コード例 #15
0
        /// <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(TargetUri 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);
        }
コード例 #16
0
        public static async Task <AuthenticationResult> GetAccessToken(this HttpContextBase context, string resource)
        {
            AuthenticationResult result = null;

            try
            {
                AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common", false, null);
                ClientCredential      creds       = new ClientCredential(CLIENT_ID, CLIENT_SECRET);
                var refreshToken = context.Request.Cookies["RefreshToken"].Value;
                result = await authContext.AcquireTokenByRefreshTokenAsync(refreshToken, creds, resource);

                //save the NEW refresh token (rolling two week expiration)
                var cookie = new HttpCookie("RefreshToken", result.RefreshToken);
                cookie.Expires = DateTime.Now.AddDays(14);
                context.Response.SetCookie(cookie);
            }
            catch (Exception)
            {
                //swallow exception and allow null result to return
            }

            return(result);
        }
コード例 #17
0
        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);
        }
コード例 #18
0
        private async Task <string> GetAzureAccessTokenAsync()
        {
            if (!string.IsNullOrWhiteSpace(GetAzureToken()))
            {
                return(GetAzureToken());
            }

            var commonToken = GetCommonAzureAccessToken();
            var tenantId    = (await GetTenantIdsAsync(commonToken.AccessToken)).FirstOrDefault();

            if (string.IsNullOrWhiteSpace(tenantId))
            {
                throw new InvalidOperationException("Unable to get tenant id for user account");
            }

            var authority            = string.Format("{0}/{1}/oauth2/authorize", GetWindowsLoginUrl(), tenantId);
            var authContext          = new AuthenticationContext(authority);
            var authenticationResult = await authContext.AcquireTokenByRefreshTokenAsync(commonToken.RefreshToken, clientId, ArmResource);

            SetAzureToken(authenticationResult);

            return(authenticationResult.AccessToken);
        }
        /// <summary>
        /// Get a Microsoft Graph access token from Azure AD.
        /// </summary>
        /// <param name="appClientId">Azure AD application client ID</param>
        /// <returns>An oauth2 access token.</returns>
        internal async Task <string> GetUserTokenAsync(string appClientId)
        {
            // For the first use get an access token prompting the user, after one hour
            // refresh silently the token
            if (_tokenForUser == null)
            {
                AuthenticationResult userAuthnResult = await _azureAdContext.AcquireTokenAsync(MicrosoftGraphResource, appClientId, new Uri(DefaultRedirectUri), PromptBehavior.Always);

                _tokenForUser = userAuthnResult.AccessToken;
                _expiration   = userAuthnResult.ExpiresOn;
                _refreshToken = userAuthnResult.RefreshToken;
            }

            if (_expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
            {
                AuthenticationResult userAuthnResult = await _azureAdContext.AcquireTokenByRefreshTokenAsync(_refreshToken, appClientId);

                _tokenForUser = userAuthnResult.AccessToken;
                _expiration   = userAuthnResult.ExpiresOn;
                _refreshToken = userAuthnResult.RefreshToken;
            }

            return(_tokenForUser);
        }
コード例 #20
0
        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);
            }
        }
コード例 #21
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <Message> Post([FromBody] Message message)
        {
            #region Check Authorization
            try
            {
                string d = (string)message.BotUserData;
                AuthenticationResult  ar = AuthenticationResult.Deserialize(d);
                AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
                ar = DateTimeOffset.Compare(DateTimeOffset.Now, ar.ExpiresOn) < 0 ? ar : await ac.AcquireTokenByRefreshTokenAsync(ar.RefreshToken, new ClientCredential(Constants.ADClientId, Constants.ADClientSecret));
            }
            catch (Exception ex)
            {
                return(message.CreateReplyMessage($"You must authenticate to use bot: https://jehollanVSBot.azurewebsites.net/api/{message.From.Id}/login"));
            }

            #endregion

            if (message.Type == "Message")
            {
                #region bot /commands
                if (Regex.IsMatch(message.Text, Constants.regex_command))
                {
                    string command = Regex.Match(message.Text, Constants.regex_command).Groups[1].Value;
                    switch (command.ToLower())
                    {
                    case "create":
                        return(createCommand(message));

                    case "topfeatures":
                        return(logicAppCommand(message, "TopFeatures"));

                    case "topbugs":
                        return(logicAppCommand(message, "TopBugs"));

                    case "topcri":
                        return(logicAppCommand(message, "TopCRI"));

                    case "currentsprint":
                        return(logicAppCommand(message, "CurrentSprint"));

                    case "start":
                        return(message.CreateReplyMessage("Please welcome your bot overlord", "en"));

                    case "logout":
                        var getData = await client.Bots.GetUserDataAsync(Constants.botId, message.From.Id);

                        getData.Data = null;
                        await client.Bots.SetUserDataAsync(Constants.botId, message.From.Id, getData);

                        return(message.CreateReplyMessage("You have been logged out"));

                    default:
                        return(message.CreateReplyMessage("Sorry, that's an invalid command", "en"));
                    }
                }
                #endregion
                else
                {
                    var reply = await Conversation.SendAsync(message, () => new VSTFDialog());

                    #region Check if I need to go start up a query or create
                    var dialogQuery  = reply.GetBotConversationData <QueryItem>("userQuery");
                    var dialogCreate = reply.GetBotConversationData <TFSItem>("userItem");
                    if (dialogQuery != null)
                    {
                        reply.SetBotConversationData("userQuery", null);
                        Task.Factory.StartNew(async() =>
                        {
                            await getQueryResults(message, dialogQuery);
                        });
                    }
                    else if (dialogCreate != null)
                    {
                        reply.SetBotConversationData("userItem", null);
                        Task.Factory.StartNew(() =>
                        {
                            createTFSItem(message, dialogCreate);
                        });
                    }

                    #endregion

                    return(reply);
                }
            }
            else
            {
                return(HandleSystemMessage(message));
            }
        }
コード例 #22
0
        public static async Task <AuthenticationResultProxy> ExecuteAsync(CommandProxy proxy)
        {
            AuthenticationResultProxy resultProxy = null;
            AuthenticationResult      result      = null;

            foreach (var command in proxy.Commands)
            {
                var arg = command.Arguments;
                switch (command.CommandType)
                {
                case CommandType.ClearDefaultTokenCache:
                {
                    var dummyContext = new AuthenticationContext("https://dummy/dummy", false);
                    dummyContext.TokenCache.Clear();
                    break;
                }

                case CommandType.SetEnvironmentVariable:
                {
                    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                    localSettings.Values[arg.EnvironmentVariable] = arg.EnvironmentVariableValue;

                    break;
                }

                case CommandType.SetCorrelationId:
                {
                    context.CorrelationId = arg.CorrelationId;
                    break;
                }

                case CommandType.CreateContextA:
                {
                    context = new AuthenticationContext(arg.Authority);
                    break;
                }

                case CommandType.CreateContextAV:
                {
                    context = new AuthenticationContext(arg.Authority, arg.ValidateAuthority);
                    break;
                }

                case CommandType.CreateContextAVT:
                {
                    TokenCache tokenCache = null;
                    if (arg.TokenCacheType == TokenCacheType.InMemory)
                    {
                        tokenCache = new TokenCache()
                        {
                            // The default token cache in ADAL WinRT is persistent. This is how to make it in-memory only cache.
                            BeforeAccess = delegate { },
                            AfterAccess  = delegate { }
                        };
                    }

                    context = new AuthenticationContext(arg.Authority, arg.ValidateAuthority, tokenCache);
                    break;
                }

                case CommandType.ClearUseCorporateNetwork:
                {
                    //context.UseCorporateNetwork = false;
                    break;
                }

                case CommandType.SetUseCorporateNetwork:
                {
                    //context.UseCorporateNetwork = true;
                    break;
                }

                case CommandType.AquireTokenAsyncRCUPa:
                {
                    UserCredential credential = new UserCredential(arg.UserName);

                    result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, credential);

                    break;
                }

                case CommandType.AquireTokenAsyncRCRe:
                {
                    result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, arg.RedirectUri);

                    break;
                }

                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.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)
            });
        }
コード例 #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TokenDetailsPage"/> class.
        /// </summary>
        public TokenDetailsPage(AuthenticationContext authCtx, TokenCacheItem token)
        {
            Button refresh, clear;
            Label  time;

            this.Title = "Token Details";

            this.Content = new StackLayout
            {
                Padding = 20,
                Spacing = 20,

                Children =
                {
                    new Label {
                        Text = token.DisplayableId
                    },
                    new Label {
                        Text = token.UniqueId
                    },
                    (time = new Label
                    {
                        Text = token.ExpiresOn.ToLocalTime().ToString(),
                        TextColor = token.ExpiresOn.ToUniversalTime() > DateTimeOffset.UtcNow ? Color.Green : Color.Red
                    }),

                    (refresh = new Button
                    {
                        Text = "Refresh",
                        TextColor = Color.White,
                        BackgroundColor = Color.FromHex("77D065"),
                    }),

                    (clear = new Button
                    {
                        Text = "Delete token",
                        TextColor = Color.White,
                        BackgroundColor = Color.FromHex("77D065"),
                    }),
                },
            };

            refresh.Clicked += async(sender, args) =>
            {
                this.IsBusy = true;

                try
                {
                    var errorMessage = string.Empty;

                    try
                    {
                        var accessToken = await authCtx.AcquireTokenSilentAsync(new UserIdentifier(token.UniqueId, UserIdentifierType.UniqueId));

                        accessToken = await authCtx.AcquireTokenByRefreshTokenAsync(accessToken);

                        time.Text      = accessToken.ExpiresOn.ToLocalTime().ToString();
                        time.TextColor = Color.Green;
                    }
                    catch (AuthenticationException e)
                    {
                        errorMessage = e.Message;
                    }

                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        await this.DisplayAlert("Sign-in failed", errorMessage, "OK");
                    }
                }
                finally
                {
                    this.IsBusy = false;
                }
            };

            clear.Clicked += (sender, args) =>
            {
                authCtx.TokenCache.DeleteItem(token);
                this.Navigation.PopAsync();
            };
        }