How do I get accounts from Azure AD?

99封情书 提交于 2019-12-24 07:39:11

问题


I have a nice Azure Active Directory set up with a dozen users. (All me!) So I have a Tenant ID, client ID and Client Secret.
I am also working on a simple console application that will function as a public client for this directory. This client also holds a list of usernames and passwords as this is just meant as a simple experiment. Not secure, I know. But I first need to understand how it works...

I do this:

IConfidentialClientApplication client = ConfidentialClientApplicationBuilder
                                  .CreateWithApplicationOptions(options).Build();

And this creates my client app. Works fine.
I also get a token using "https://graph.microsoft.com/.default" and can use this to get all users as JSON:

string result = await GetHttpContentWithToken("https://graph.microsoft.com/v1.0/users", 
                                               token.AccessToken);

Although I might want it to be more user-friendly, JSON is fine for now.

How can I check if user is an authorized user?
And no, I don't want complex solutions that require various nuget packages. Just a plain and simple step-by-step explanation. I could probably Google this but I ended up with thousands of results and none were helpful... This should be easy, right?

[EDIT] I first wanted to get a list of users nut that failed because of a typo... (There's a dot before 'default'...)


回答1:


It took some fooling around but it's not too difficult after all. There are a lot of libraries around Azure but it is all basically just a bunch of HTTP requests and responses. Even in a console application... I started with making a PublicClientApplicationBuilder first:

var options = new PublicClientApplicationOptions()
{
    ClientId = <**clientid**>,
    TenantId = <**tenantid**>,
    AzureCloudInstance = AzureCloudInstance.AzurePublic,
};
var client = PublicClientApplicationBuilder.CreateWithApplicationOptions(options).Build();

I can also create a ConfidentialClientApplication instead, but this allows me to log in interactively, if need be.

Next, set up the scopes:

var scopes = new List<string>() { "https://graph.microsoft.com/.default" };

As I wanted to log in using username and password, I have to use this:

var token = await client.AcquireTokenInteractive(scopes).ExecuteAsync();

But if I want to log in using code, I can also use this:

var password = new SecureString();
foreach (var c in <**password**>) { password.AppendChar(c); }
var token = await client.AcquireTokenByUsernamePassword(scopes, <**account**>, password).ExecuteAsync();

At this point, I'm authorized as the specified user. So, now all I need is to get whatever data I like, in JSON strings...

public static async Task<string> ExecCmd(string name, string url, string token)
{
    HttpClient httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
    string result = await GetHttpContentWithToken(url, token);
    JObject json = JsonConvert.DeserializeObject(result) as JObject;
    File.WriteAllText(name, json.ToString());
    return result;
}

As I just want to read the data as text files, I just execute the action in using a specific and write it as formatted JSON to the file . So, using this simple method I can now use this:

await ExecCmd("Profile.txt", "https://graph.microsoft.com/v1.0/me/", token.AccessToken);
await ExecCmd("Groups.txt", "https://graph.microsoft.com/v1.0/groups", token.AccessToken);
await ExecCmd("Users.txt", "https://graph.microsoft.com/v1.0/users", token.AccessToken);

These will provide me with (1) the profile of the current user, (2) the AD groups and (3) the AD users. And probably a bit more... I can use this ExecCmd to retrieve a lot more data, if I want to. But there's something else to keep in mind! For it all to work, you also need to configure the Azure application and make sure all access rights are assigned and approved! So, in Azure AD you have to add an "App registration" and fiddle around with the settings... (The Azure experts are horribly shocked now, but when you want to learn, you'd just have to try and fail until you succeed...) Also set "Default client type" to "public client" for the registered app. In Azure, with the registered app, you also need to set the proper API permissions! Otherwise, you won't have access. And as I want access to Active Directory, I need to add permissions to "Azure Active Directory Graph". I can do this inside Azure or by using the scope when I call AcquireTokenInteractive(). For example, by using "https://graph.windows.net/Directory.Read.All" instead of "https://graph.windows.net/.default". Once you've accessed a token interactively, you can also get more tokens using client.AcquireTokenSilent(). It gets a bit tricky from here, especially if you want to access a lot of different items. Fortunately, Active Directory is mostly the directory itself, groups, users and members. Personally, I prefer to grant access from the Azure website but this is quite interesting. Anyways, I wanted to authenticate users with Azure and now I know how to do this. It still leaves a lot more questions but this all basically answers my question... I'll use this as answer, as others might find it useful...



来源:https://stackoverflow.com/questions/56444669/how-do-i-get-accounts-from-azure-ad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!