35

This is how I have written code and trying to get the output.

The request body must contain the following parameter: client_secret or client_assertion

 static async Task<AuthenticationResult> getAccessToken()
 {
     string hardcodedUsername = "";
     string hardcodedPassword = "";
     string tenantName = "projectwidgets.com";
     string authString = "https://login.microsoftonline.com/" + tenantName;
     AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
     //Config for OAuth client credentials
     string clientId = "as";
     string key = "kk";
     string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenantName);
     var authContext = new AuthenticationContext(authority);
     AuthenticationResult result = null;
     try
     {
         result = await authContext.AcquireTokenAsync("https://pwsnapitazure.azurewebsites.net", clientId, new UserPasswordCredential(hardcodedUsername, hardcodedPassword));
     }
     catch (Exception ex)
     {
          Console.WriteLine(ex.StackTrace);
          System.Diagnostics.Debug.WriteLine(ex.Message);
     }                        
     return result;
 }
TylerH
  • 20,799
  • 66
  • 75
  • 101
ravi rathod
  • 461
  • 1
  • 4
  • 6

3 Answers3

54

As the Azure App Registration UI has changed from legacy authentication, you will need to enable an additional setting called "treat application as a public client". Under Default Client Type, set this setting to Yes:

screenshot of AAD App Registration showing "Treat application as a public client" set to "yes" under the 'Default client type' subsection of the 'Advanced Settings' section

In the Manifest also you can control this by setting:

"allowPublicClient": true

Update 2022:

UI name changed to Allow public client flows

enter image description here

Jayendran
  • 9,638
  • 8
  • 60
  • 103
  • 2
    This worked for me and Postman once I'd added the Postman return URL to the "Mobile and Desktop Application" redirect rather than "Web". – Zhaph - Ben Duguid Jul 20 '22 at 18:30
  • And one more thing removing the callback URL if you added it – LordDraagon Oct 26 '22 at 17:52
  • 3
    2022 Update and for those who landed here after following this tutorial: https://learn.microsoft.com/en-us/azure/active-directory/develop/desktop-app-quickstart?pivots=devlang-uwp you need to `Allow public client flows`, which is located where Jayendran shows (the name has changed but the button is the same). – Ama Nov 27 '22 at 00:41
10

According to your code , that seems you are using a web app/API that uses username and password to authenticate .

we can only use the resource owner flow from a native client. A confidential client, such as a web site, cannot use direct user credentials.

You would need to invoke it as a public client (native client app), not as a confidential client (web app/API). Please refer to this document for more about how to use ADAL .NET to authenticate users via username/password .Especially the Constraints & Limitations section .

In daemon or server application , you may consider using client credential flow , but with this flow, the application presents its client credentials to the OAuth2 token issuing endpoint, and in return gets an access token that represents the application itself without any user information. Please click here for more details about client credential flow , and here are code samples.

Nan Yu
  • 26,101
  • 9
  • 68
  • 148
-1

i used below given code and it worked for me .

            public static async Task<string> AccessToken2()
    {
        string token = "";
        var appSettings = ConfigurationManager.AppSettings;

        string m_authorityUrl   = appSettings["authorityUrl"] ?? "Not Found";
        string[] m_scope        = appSettings["scope"].Split(';') ?? null;
        string ApplicationId    = appSettings["applicationId"];
        string WorkspaceId      = appSettings["workspaceId"];
        string ReportId         = appSettings["reportId"];
        string AuthenticationType = appSettings["authenticationType"];
        string ApplicationSecret = appSettings["applicationSecret"];
        string Tenant           = appSettings["tenant"];
        string Username         = appSettings["pbiUsername"];
        string Password         = appSettings["pbiPassword"];




    Microsoft.Identity.Client.AuthenticationResult authenticationResult = null;

        try
        {

            if (ConfigValidatorService.AuthenticationType.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase))
            {
                // For app only authentication, we need the specific tenant id in the authority url
                var tenantSpecificURL = m_authorityUrl.Replace("organizations", ConfigValidatorService.Tenant);

                IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
                                                                                .Create(ConfigValidatorService.ApplicationId)
                                                                                .WithClientSecret(ConfigValidatorService.ApplicationSecret)
                                                                                .WithAuthority(tenantSpecificURL)
                                                                                .Build();

                authenticationResult = await clientApp.AcquireTokenForClient(m_scope).ExecuteAsync();

                MessageBox.Show(authenticationResult.AccessToken);
            }


        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message.ToString());
        }

        return token;

    }

and

              <appSettings>
             
                <add key="webpages:Version" value="3.0.0.0" />
                <add key="webpages:Enabled" value="false" />
                <add key="ClientValidationEnabled" value="true" />
                <add key="UnobtrusiveJavaScriptEnabled" value="true" />

                <!-- Two possible Autentication method: 
                      - For authentication with master user credential choose MasterUser as AuthenticationType.
                      - For authentication with app secret choose ServicePrincipal as AuthenticationType.
                        More details here: https://docs.microsoft.com/en-us/power-bi/developer/embed-service-principal
                    -->
                <add key="authenticationType" value="ServicePrincipal" />
                <!-- Common configuration properties for both authentication types -->
                <add key="applicationId" value="31e7262c464b" />
                <add key="workspaceId" value="b35a9bdbbe43" />
                <add key="reportId" value="b7d9-da713912dca2" />

                <!-- Fill Tenant ID in authorityUrl-->
                <add key="authorityUrl" value="https://login.microsoftonline.com/organizations/" />
                <add key="scope" value="https://analysis.windows.net/powerbi/api/.default" />
                <add key="urlPowerBiServiceApiRoot" value="https://api.powerbi.com/" />

                <!-- Note: Do NOT leave your credentials on code. Save them in secure place like Key Vault. -->
                <add key="pbiUsername" value="hfhg@jhgjj.onmicrosoft.com" />
                <add key="pbiPassword" value="gfhghgfh" />

                <!-- Note: Do NOT leave your app secret on code. Save it in secure place like Key Vault. -->
                <add key="applicationSecret" value="JhTQCaMx" />
                <add key="tenant" value="647587" />

              </appSettings>
            </configuration>