40465

AuthenticationContext.AcquireTokenAsync new to C#

Question:

I am new to Azure and would like to be programmatically able to get a token from Azure. Whatever I do though, it seems to fail - does anyone have a working example? Thanks guys

I call GetAToken().Wait();.

and the method is:

public async Task<string> GetAToken() { // authentication parameters string clientID = "*********"; string username = "<azure login>"; string password = "<azure login password>"; string directoryName = "<AD Domain name>"; ClientCredential cc = new ClientCredential(clientID, password); var authenticationContext = new AuthenticationContext("https://login.windows.net/" + directoryName); AuthenticationResult result = await authenticationContext.AcquireTokenAsync("https://management.core.windows.net/", cc); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } string token = result.AccessToken; return token; }

Answer1:

So not sure if you are doing this on Android, iOS or Xamarin.Forms. Below is how I will authenticate with ADAL and Azure (the code is working on my end):

On Android:

public async Task<AuthenticationResult> Authenticate(Activity context, string authority, string resource, string clientId, string returnUri) { var authContext = new AuthenticationContext(authority); if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); var uri = new Uri(returnUri); var platformParams = new PlatformParameters(context); try { var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams); return authResult; } catch (AdalException e) { return null; } }

On iOS:

public async Task<AuthenticationResult> Authenticate(UIViewController controller, string authority, string resource, string clientId, string returnUri) { var authContext = new AuthenticationContext(authority); if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); var controller = UIApplication.SharedApplication.KeyWindow.RootViewController; var uri = new Uri(returnUri); var platformParams = new PlatformParameters(controller); try { var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams); return authResult; } catch (AdalException e) { return null; } }

On <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-dotnet" rel="nofollow">UWP</a>:

public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri) { var authContext = new AuthenticationContext(authority); if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); var uri = new Uri(returnUri); var platformParams = new PlatformParameters(PromptBehavior.Auto); try { var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams); return authResult; } catch (AdalException e) { return null; } }

Variable that I pass into the methods above:

string authority = "https://login.windows.net/common"; string ResourceID = "Backend ClientId";//Backend (web app) string clientId = "Native App ClientId";//native app string returnUri = "https://{My Azure Site}.azurewebsites.net/.auth/login/done";

If you want to do this in Xamarin.Forms, below are links to my GitHub solution where I have exposed these methods through the DependencyService.

<ul><li><a href="https://github.com/michael-watson/Azure-MyExpenses/blob/master/MyExpenses.Mobile/MyExpenses/Interfaces/IAuthenticator.cs" rel="nofollow">PCL implementation</a></li> <li><a href="https://github.com/michael-watson/Azure-MyExpenses/blob/master/MyExpenses.Mobile/iOS/Authenticator_iOS.cs" rel="nofollow">iOS implementation</a></li> <li><a href="https://github.com/michael-watson/Azure-MyExpenses/blob/master/MyExpenses.Mobile/Droid/Authenticator_Droid.cs" rel="nofollow">Android Implementation</a></li> </ul>

I hope this helps! If you get any errors from your response, check to make sure you have your permissions setup in Azure correctly. I do it like <a href="https://github.com/michael-watson/Azure-MyExpenses#3-authorizationauthentication-service" rel="nofollow">this</a>. Another great resource is <a href="https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/" rel="nofollow">Adrian Hall's Xamarin/Azure book</a>

<h2>EDIT: Added UWP stuff</h2>

Answer2:

If what you are trying to do is call the Azure APIs as you, there are a few things you should do differently.

<ol><li>Create an app in Azure AD that has permissions to access the Azure API <ol><li>If you want to call Service Management API, then add that as a permission <ol><li>You could also alternatively use a management certificate</li> </ol></li> <li>If you want to call Resource Management API, then add the permissions needed to the service principal through the new Portal</li> </ol></li> <li>If you chose the delegated way for Service Management API (the first option), then you will have to either: <ol><li>Have the user authenticate against Azure AD with the Authorization Code Grant flow</li> <li>Or get the access token using the Password grant flow (you can see an example of this in <a href="https://stackoverflow.com/a/41159005/1658906" rel="nofollow">another answer</a></li> </ol></li> <li>If instead you chose a management certificate or giving the permissions to the service principal, then you can get the access token directly from Azure AD using the Client credentials grant flow</li> </ol>

In the end you will always end up with an access token that you can use for calling the API.

Answer3:

IF you're using the wrappers, ensure to have the correct version-Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612. Once referenced, you can run this below. For alternatives, see this blog: <a href="https://samtran.me/2018/11/11/power-bi-rest-api/" rel="nofollow">https://samtran.me/2018/11/11/power-bi-rest-api/</a>

Recommend

  • sqlcmd: Login failed for user 'NT AUTHORITY\\ANONYMOUS LOGON'
  • Is there a bug in java.net.SocketPermission when dealing with cname reverse lookup
  • Strip protocol and subdomain from a URL
  • WMI.NET to MicrosoftBizTalkServer - Login failed for user ANONYMOUS LOGIN
  • Import ios certification error, “This certificate was signed by an unknown authority”.
  • How to validate self-signed certification
  • MSI installer custom action identity problem
  • Connecting php to MS SQL Server. Login failed
  • SSL error RemoteCertificateNameMismatch
  • Datatables: custom function inside of fnRowCallback
  • using class interface as a parameter in wcf service
  • connecting to web api using c#
  • Get Current Windows User VB.net
  • Google script gmail addon update TextInput value,on change function
  • Slim Framework Method not allowed. Must be one of: POST (405)
  • Office365 authentication without login redirection
  • cURL for Windows can't make a secure connection to the Stack API
  • Clickable Webcontrol, ASP.NET
  • SSLRead() return error -9806/15958)
  • Deploying pre-encrypted configuration files to a production environment
  • How many Vertica Databases can run on a Host in the same time?
  • How to change placeholder text in an autocomplete activity of android google place?
  • ASP.NET windows authentication should always ask for credentials
  • EditText is covered by Keyboard
  • In Java, how can I construct a File from a resource?
  • Authentication failed with Azure Active Directory in Windows Phone
  • JPA flush vs commit
  • URLConnection doesn't work since API 10 and higher?
  • Elasticsearch script query involving root and nested values
  • Why use database factory in asp.net mvc?
  • How do I configure context broker accept post requests from my remote sensor?
  • JBoss External Properties Files in Classpath
  • Unity3D & Android: Difference between “UnityMain” and “main” threads?
  • Launch Runnable Jar from Web Start
  • script to move all files from one location to another location
  • Javascript Callbacks with Object constructor
  • In LanguageTool, how do you create a dictionary and use it for spell checking?
  • unknown Exception android