Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. private async Task<string> GetAccessTokenAsync()
  2. {
  3. string _accessToken = null;
  4. DateTime _accessTokenExpiry = DateTime.MinValue;
  5. if (_accessToken != null && DateTime.UtcNow < _accessTokenExpiry)
  6. {
  7. return _accessToken;
  8. }
  9.  
  10. using (HttpClient client = new HttpClient())
  11. {
  12. var discoveryRequest = new DiscoveryDocumentRequest
  13. {
  14. Address = "https://staging.osipi.com/identity",
  15. Policy = new DiscoveryPolicy
  16. {
  17. Authority = "https://identity.osisoft.com",
  18. ValidateEndpoints = false,
  19. ValidateIssuerName = false
  20. }
  21. };
  22.  
  23. var discoveryResponse = await client.GetDiscoveryDocumentAsync(discoveryRequest);
  24.  
  25. if (discoveryResponse.IsError)
  26. throw new InvalidOperationException(discoveryResponse.Error);
  27.  
  28. var clientCredentialsTokenRequest = new ClientCredentialsTokenRequest
  29. {
  30. Address = discoveryResponse.TokenEndpoint,
  31. ClientId = "cf8611cc-d754-4a42-802c-b4500506a718",
  32. ClientSecret = "LyzBLtHl56LOskMfke9l74dk5Y4Cts4kJVxQgWSeRSQ=",
  33. Scope = "ocsapi"
  34. };
  35.  
  36. DateTime now = DateTime.UtcNow;
  37.  
  38. var tokenResponse = await client.RequestClientCredentialsTokenAsync(clientCredentialsTokenRequest);
  39.  
  40. if (discoveryResponse.IsError)
  41. throw new InvalidOperationException(tokenResponse.Error);
  42.  
  43. if (string.IsNullOrEmpty(tokenResponse.AccessToken))
  44. throw new InvalidOperationException("Failed to acquire Access Token");
  45.  
  46. _accessToken = tokenResponse.AccessToken;
  47.  
  48. // Add a buffer of 30 seconds to the expiration delta.
  49. _accessTokenExpiry = now.AddSeconds(tokenResponse.ExpiresIn - 30);
  50.  
  51. return _accessToken;
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement