How to authorize in Azure Active Directory without using dialog?

爱⌒轻易说出口 提交于 2019-12-02 07:22:53

I did this once without using ADAL. For Power BI as well, since they don't offer application permissions, only delegated.

What you need to is call the AAD token endpoint with grant_type=password. You will specify the username and password, as well as the client id, client secret and resource URI in form parameters.

Here is the function I wrote:

private async Task<string> GetAccessToken()
{
    string tokenEndpointUri = Authority + "oauth2/token";

    var content = new FormUrlEncodedContent(new []
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", Username),
            new KeyValuePair<string, string>("password", Password),
            new KeyValuePair<string, string>("client_id", ClientId),
            new KeyValuePair<string, string>("client_secret", ClientSecret),
            new KeyValuePair<string, string>("resource", PowerBiResourceUri)
        }
    );

    using (var client = new HttpClient())
    {
        HttpResponseMessage res = await client.PostAsync(tokenEndpointUri, content);

        string json = await res.Content.ReadAsStringAsync();

        AzureAdTokenResponse tokenRes = JsonConvert.DeserializeObject<AzureAdTokenResponse>(json);

        return tokenRes.AccessToken;
    }
}

Authority here is https://login.microsoftonline.com/tenant-id/. Here is the response class I'm using:

class AzureAdTokenResponse
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }
}

I hope using UserCreadential you have give username and password of azure subscription and you can get AccessToken and call your api. i hope it should helps you.

 string ResourceUrl="https://analysis.windows.net/powerbi/api";
 string ClientId=Properties.Settings.Default.ClientID;//as per your code
 AuthenticationContext authenticationContext = new AuthenticationContext(Constants.AuthString, false);
 UserCredential csr = new UserCredential("your-username", "password");
 AuthenticationResult authenticationResult = authenticationContext.AcquireToken(ResourceUrl,ClientId, usr);
 string token = authenticationResult.AccessToken;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!