简体   繁体   中英

Login to api teams without login and password

I have problem with my code. I would like to do that the login window (as in the picture) oppear only once when I loggin in. And the next time, when I start the program, login and password would be remembered. What change in my program that this login window doesn't pop up? Or how do I do a domain login?
Here is my code

code

login window

private static async System.Threading.Tasks.Task DodajSpotkanieDoTeamsAsync(Spotkanie spotkanie)
    {
        AuthenticationResult authResult = null;
        var app = App.PublicClientApp;

        var accounts = await app.GetAccountsAsync();
        var firstAccount = accounts.FirstOrDefault();

        try
        {
            authResult = await app.AcquireTokenSilent(scopes, firstAccount)
                .ExecuteAsync();
        }
        catch (MsalUiRequiredException ex)
        {
            try
            {
                authResult = await app.AcquireTokenInteractive(scopes)
                    .WithAccount(accounts.FirstOrDefault())
                    .ExecuteAsync();
            }
            catch (MsalException msalex)
            {
            }
        }
        catch (Exception ex)
        {
            return;
        }

        if (authResult != null)
        {
            GraphServiceClient graphClient = new GraphServiceClient(
                "https://graph.microsoft.com/v1.0",
                new DelegateAuthenticationProvider(
                    async (requesMessage) =>
                    {
                        requesMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", authResult.AccessToken);
                    }));

            var @event = new Event
            {
                Subject = spotkanie.Tytul,
                Body = new ItemBody
                {
                    ContentType = BodyType.Html,
                },
                Start = new DateTimeTimeZone
                {
                    DateTime = spotkanie.DataRozpoczecia,
                    TimeZone = "Pacific Standard Time"
                },
                End = new DateTimeTimeZone
                {
                    DateTime = spotkanie.DataZakonczenia,
                    TimeZone = "Pacific Standard Time"
                },

                IsOnlineMeeting = true,
                OnlineMeetingProvider = OnlineMeetingProviderType.TeamsForBusiness
            };

            var listaGosci = new List<Attendee>();
            foreach (var gosc in spotkanie.ListaGosci.Split('|'))
            {
                listaGosci.Add(
                    new Attendee
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = gosc
                        },
                    }
                    );
            }

            @event.Attendees = listaGosci;

            try
            {
                var request = await graphClient.Me.Calendar.Events
                .Request()
                .AddAsync(@event);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

Instead of acquiring a token using build in function you can build your own login form and cache the data (login and pw) and use it in a REST call to get the token:

var client = new RestClient("https://login.microsoftonline.com/" + domainname);
var request = new RestRequest("/oauth2/token", Method.POST);   request.AddBody("grant_type", "client_credentials");
request.AddParameter("client_id", clientId);
request.AddParameter("client_secret", clientSecret);
request.AddParameter("Resource", "https://graph.microsoft.com");
request.AddParameter("scope", "[scopes]"); 
IRestResponse response = client.Execute(request);

var token= response.Content;

To store credentials securely use Windows Credential Management:

{   
public static UserPass GetCredential(string target)
    {
        var cm = new Credential {Target = target};
        if (!cm.Load())
        {
            return null;
        }
        return new UserPass(cm.Username, cm.Password);
    }
    
    public static bool SetCredentials(string target, string username, string password, PersistanceType persistenceType)
    {
        return new Credential {Target = target,
                Username = username,
                Password = password,
                PersistanceType =  persistenceType}.Save();
    }
    
    public static bool RemoveCredentials(string target)
    {
        return new Credential { Target = target }.Delete();
    }
}


CredentialUtil.SetCredentials("FOO", "john", "1234", PersistanceType.LocalComputer);
var userpass = CredentialUtil.GetCredential("FOO");
Console.WriteLine($"User: {userpass.Username} Password: {userpass.Password}");
CredentialUtil.RemoveCredentials("FOO");
Debug.Assert(CredentialUtil.GetCredential("FOO") == null);

for .net PM command :

Install-Package CredentialManagement -Version 1.0.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM