Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 views
in Technique[技术] by (71.8m points)

asp.net mvc - How to authorize in Azure Active Directory without using dialog?

My application shows dashboard of my power bi account for all users, I am authorizing the Azure Active Directory through a dialog to get an access token. Can I hard code my credentials and get access token without using the authorization dialog. Code. It works but it is using the authorization dialog.

           var @params = new NameValueCollection
        {
            {"response_type", "code"},
            {"client_id", Properties.Settings.Default.ClientID},
            {"resource", "https://analysis.windows.net/powerbi/api"},
            {"redirect_uri", "http://localhost:13526/Redirect"}
        };


        var queryString = HttpUtility.ParseQueryString(string.Empty);
        queryString.Add(@params);

        string authorityUri = "https://login.windows.net/common/oauth2/authorize/";
        var authUri = String.Format("{0}?{1}", authorityUri, queryString);
        Response.Redirect(authUri);


        Redirect.aspx
        string redirectUri = "http://localhost:13526/Redirect";
        string authorityUri = "https://login.windows.net/common/oauth2/authorize/";

        string code = Request.Params.GetValues(0)[0];

        TokenCache TC = new TokenCache();

        AuthenticationContext AC = new AuthenticationContext(authorityUri, TC);
        ClientCredential cc = new ClientCredential
            (Properties.Settings.Default.ClientID,
            Properties.Settings.Default.ClientSecret);

        AuthenticationResult AR = AC.AcquireTokenByAuthorizationCode(code, new Uri(redirectUri), cc);

        Session[_Default.authResultString] = AR;

        Response.Redirect("/Default.aspx");
        Default.aspx
         string responseContent = string.Empty;

        System.Net.WebRequest request = System.Net.WebRequest.Create(String.Format("{0}dashboards", baseUri)) as System.Net.HttpWebRequest;
        request.Method = "GET";
        request.ContentLength = 0;
        request.Headers.Add("Authorization", String.Format("Bearer {0}", authResult.AccessToken));

        using (var response = request.GetResponse() as System.Net.HttpWebResponse)
        {
            using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
            {
                responseContent = reader.ReadToEnd();
                PBIDashboards PBIDashboards = JsonConvert.DeserializeObject<PBIDashboards>(responseContent);
            }
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...