コード例 #1
0
        private async Task InitializeToken()
        {
            if (!string.IsNullOrWhiteSpace(token))
            {
                return;
            }

            var cacheToken = appCache.GetString(tokenKey);

            if (!string.IsNullOrWhiteSpace(cacheToken))
            {
                token = cacheToken;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Token is retrieved from cache");
                Console.ResetColor();
                return;
            }

            var idServer = idServerUrl;

            var discDoc = await client.GetDiscoveryDocumentAsync(idServer);

            if (discDoc.IsError)
            {
                var error = "Could not get the ID-Server information.";
                if (discDoc.Exception != null)
                {
                    error += $" Error{discDoc.Exception.Message}";
                }

                throw new Exception(error);
            }

            var scopes = new Dictionary <string, string>
            {
                { "scope", "catalog.fullaccess" }
            };

            var request = new TokenRequest
            {
                Address      = discDoc.TokenEndpoint,
                GrantType    = "client_credentials",
                Parameters   = scopes,
                ClientId     = "mg.website",
                ClientSecret = "1e230c33-6de2-4755-bcbf-333f1afe1ff2"
            };

            var tokenResult = await client.RequestTokenAsync(request);

            if (tokenResult.IsError)
            {
                var error = "Could not get the auth token from ID-Server.";
                if (tokenResult.Exception != null)
                {
                    error += $" Error{tokenResult.Exception.Message}";
                }

                throw new Exception(error);
            }

            this.token = tokenResult.AccessToken;
            appCache.SetString(tokenKey, tokenResult.AccessToken,
                               TimeSpan.FromSeconds(tokenResult.ExpiresIn - 10));

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("Token is retrieved from ID-Server");
            Console.ResetColor();
        }