How do I get an OAuth 2.0 authentication token in C#

后端 未结 7 1215
借酒劲吻你
借酒劲吻你 2020-12-02 11:15

I have these settings:

  • Auth URL (which happens to be a \"https://login.microsoftonline.com/...\") if that helps.
  • Access Token URL \"https://service.en
7条回答
  •  醉酒成梦
    2020-12-02 11:51

    I used ADAL.NET/ Microsoft Identity Platform to achieve this. The advantage of using it was that we get a nice wrapper around the code to acquire AccessToken and we get additional features like Token Cache out-of-the-box. From the documentation:

    Why use ADAL.NET ?

    ADAL.NET V3 (Active Directory Authentication Library for .NET) enables developers of .NET applications to acquire tokens in order to call secured Web APIs. These Web APIs can be the Microsoft Graph, or 3rd party Web APIs.

    Here is the code snippet:

        // Import Nuget package: Microsoft.Identity.Client
        public class AuthenticationService
        {
             private readonly List _scopes;
             private readonly IConfidentialClientApplication _app;
    
            public AuthenticationService(AuthenticationConfiguration authentication)
            {
    
                 _app = ConfidentialClientApplicationBuilder
                             .Create(authentication.ClientId)
                             .WithClientSecret(authentication.ClientSecret)
                             .WithAuthority(authentication.Authority)
                             .Build();
    
               _scopes = new List {$"{authentication.Audience}/.default"};
           }
    
           public async Task GetAccessToken()
           {
               var authenticationResult = await _app.AcquireTokenForClient(_scopes) 
                                                    .ExecuteAsync();
               return authenticationResult.AccessToken;
           }
       }
    

提交回复
热议问题