Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wait for token device code / new Sample for Authentication #594

Open
tehho opened this issue Feb 15, 2019 · 0 comments
Open

Wait for token device code / new Sample for Authentication #594

tehho opened this issue Feb 15, 2019 · 0 comments
Assignees
Labels
investigate firther investigation needed before we cna prceed with this issue Mgmt Management plane SDK related issues.

Comments

@tehho
Copy link

tehho commented Feb 15, 2019

I have tried to get the device code to work and have now managed a manuall way to do it and would like to have an automated way.

What i've done is to write the device message and then waiting with a readline and the returning true.

What i would like to do is to peek at the token to see if it's ready to fetch.
When i try to do this I automaticly fetch the token and then i get an error saying the token is already claimed.

Tried to refresh token as a work around but that to fetched the token directly.
Good to have for some systems but not nice when you want a smoot signin process in your application.

`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace azure_check_subnet_without_nsg
{
class Program
{
private const string TenantId = "YOUR-TENANT-HERE";

    static async Task Main(string[] args)
    {

        var deviceInfo = new DeviceCredentialInformation();
        deviceInfo.ClientId = "YOUR-NATIVE-APP-ID-HERE";
        deviceInfo.DeviceCodeFlowHandler = d => ConnectToAzureAsync(d).Result;

        var userCred = new AzureCredentials(deviceInfo, TenantId, AzureEnvironment.AzureGlobalCloud);

        var azure = Azure
            .Configure()
            .Authenticate(userCred);
        
        var subs = await azure.Subscriptions.ListAsync();




        subs.Select(sub => azure.WithSubscription(sub.SubscriptionId))
            .SelectMany(sub => sub.Networks.ListAsync().Result)
            .SelectMany(vnet => vnet.Subnets)
            .Where(subnet => (subnet.Value.NetworkSecurityGroupId == null))
            .ToList()
            .ForEach(subnet =>
            {
                var vnet = subnet.Value.Parent;
                var subscriptionId = vnet.Manager.SubscriptionId;
                var subscription = azure.Subscriptions.GetById(subscriptionId);

                Console.WriteLine($"Subscription: {subscription.DisplayName} Vnet: {vnet.Name} Subnet: {subnet.Value.Name}");
            });
    }

    static async Task<IEnumerable<INetwork>> GetAllVnet(Azure.IAuthenticated azure, ISubscription subscription)
    {
        return await azure.WithSubscription(subscription.SubscriptionId).Networks.ListAsync();
    }

    static async Task<IEnumerable<ISubnet>> GetAllSubnetWithoutNsgAsync(INetwork vnet)
    {
        return await new Task<IEnumerable<ISubnet>>(() => vnet.Subnets.Select(vn => vn.Value).Where(subnet => subnet.NetworkSecurityGroupId == null));
    }

    static void PrintSubscriptionVnetSubnet(ISubscription subscription, INetwork vnet, ISubnet subnet)
    {   
        Console.WriteLine($"Subscription: {subscription.DisplayName} Vnet: {vnet.Name} Subnet: {subnet.Name}");
    }

    static async Task<bool> ConnectToAzureAsync(DeviceCodeResult device)
    {
        Console.WriteLine(device.Message);

        //Console.ReadLine();

        //return true;

        var pollingInterval = TimeSpan.FromSeconds(device.Interval);
        var codeExpiresOn = device.ExpiresOn;
        
        var timeRemaining = codeExpiresOn - DateTimeOffset.UtcNow;

        string tokenUri = string.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{1}/oauth2/token", device.Resource, TenantId);

        while(timeRemaining.TotalSeconds > 0)
        {
            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUri)
            {
                Content = new FormUrlEncodedContent(
                    new Dictionary<string, string>()
                    {
                        ["grant_type"] = "device_code",
                        ["resource"] = device.Resource,
                        ["code"] = device.DeviceCode,
                        ["client_id"] = device.ClientId
                    }
              )
            };

            using (var client = new HttpClient())
            {
                var tokenRes = await client.SendAsync(tokenRequest);

                if (tokenRes.IsSuccessStatusCode)
                {
                    var tokenJson = await tokenRes.Content.ReadAsStringAsync();

                    var tokenData = JObject.Parse(tokenJson);

                    var token = tokenData["refresh_token"];

                    tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUri)
                    {
                        Content = new FormUrlEncodedContent(
                            new Dictionary<string, string>()
                            {
                                ["grant_type"] = "refresh_token",
                                ["resource"] = device.Resource,
                                ["refresh_token"] = token.ToString(),
                                ["client_id"] = device.ClientId
                            }
                        )
                    };

                    tokenRes = await client.SendAsync(tokenRequest);

                    return true;
                }
            }

            await Task.Delay((int)pollingInterval.TotalMilliseconds);
        }

        return false;
    }
}

}

`

@praries880 praries880 added Az Net SDK Team Issues assigned to the Azure Net SDK team investigate firther investigation needed before we cna prceed with this issue labels Feb 27, 2019
@praries880 praries880 added Mgmt Management plane SDK related issues. and removed Az Net SDK Team Issues assigned to the Azure Net SDK team labels Mar 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
investigate firther investigation needed before we cna prceed with this issue Mgmt Management plane SDK related issues.
Projects
None yet
Development

No branches or pull requests

3 participants